mirror of
https://github.com/open-metadata/OpenMetadata.git
synced 2025-10-16 11:18:33 +00:00
[DuplicateLogin] User name issue for loggedInUserApi (#16762)
* User Email Based lookup for loggedInUser * Add Unique on name * support email only login * fix cypress * fix playwright * reset user for 404 inject enableSelfSignup for auth config * Add Self Signup Flag * Add error messages * Better check * Change to Custom Exception Message * Update message as suggested * fix claim issue for confidential type * fix sonar --------- Co-authored-by: Chira Madlani <chirag@getcollate.io>
This commit is contained in:
parent
12b227b7e3
commit
b05d29ccee
@ -0,0 +1 @@
|
||||
ALTER TABLE user_entity ADD UNIQUE (name);
|
@ -0,0 +1 @@
|
||||
ALTER TABLE user_entity ADD UNIQUE (name);
|
@ -81,6 +81,12 @@ public final class CatalogExceptionMessage {
|
||||
|
||||
public static final String SELF_SIGNUP_NOT_ENABLED = "SELF_SIGNUP_NOT_ENABLED";
|
||||
public static final String SELF_SIGNUP_ERROR = "Signup is not supported.";
|
||||
public static final String OTHER_USER_SIGN_UP_ERROR = "OTHER_USER_SIGN_UP_ERROR";
|
||||
public static final String OTHER_USER_SIGN_UP =
|
||||
"Self Signup can only create user for self. Only Admin can create other users.";
|
||||
public static final String SELF_SIGNUP_DISABLED_MESSAGE =
|
||||
"Self Signup is not enabled. Please contact your Administrator for assistance with account creation";
|
||||
|
||||
public static final String NOT_IMPLEMENTED_METHOD = "Method not implemented.";
|
||||
|
||||
public static final String AUTHENTICATOR_OPERATION_NOT_SUPPORTED =
|
||||
|
@ -126,8 +126,13 @@ public class UserRepository extends EntityRepository<User> {
|
||||
if (userString == null) {
|
||||
throw EntityNotFoundException.byMessage(CatalogExceptionMessage.entityNotFound(USER, email));
|
||||
}
|
||||
return withHref(
|
||||
uriInfo, setFieldsInternal(JsonUtils.readValue(userString, User.class), fields));
|
||||
User user = JsonUtils.readValue(userString, User.class);
|
||||
setFieldsInternal(user, fields);
|
||||
setInheritedFields(user, fields);
|
||||
// Clone the entity
|
||||
User entityClone = JsonUtils.deepCopy(user, User.class);
|
||||
clearFieldsInternal(entityClone, fields);
|
||||
return withHref(uriInfo, entityClone);
|
||||
}
|
||||
|
||||
/** Ensures that the default roles are added for POST, PUT and PATCH operations. */
|
||||
@ -321,9 +326,9 @@ public class UserRepository extends EntityRepository<User> {
|
||||
return findTo(teamId, TEAM, Relationship.PARENT_OF, TEAM);
|
||||
}
|
||||
|
||||
public List<EntityReference> getGroupTeams(UriInfo uriInfo, String userName) {
|
||||
public List<EntityReference> getGroupTeams(UriInfo uriInfo, String email) {
|
||||
// Cleanup
|
||||
User user = getByName(uriInfo, userName, Fields.EMPTY_FIELDS, Include.ALL, true);
|
||||
User user = getByEmail(uriInfo, email, Fields.EMPTY_FIELDS);
|
||||
List<EntityReference> teams = getTeams(user);
|
||||
return getGroupTeams(teams);
|
||||
}
|
||||
|
@ -15,6 +15,7 @@ package org.openmetadata.service.resources.teams;
|
||||
|
||||
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
|
||||
import static javax.ws.rs.core.Response.Status.CONFLICT;
|
||||
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
|
||||
import static javax.ws.rs.core.Response.Status.OK;
|
||||
import static org.openmetadata.common.utils.CommonUtil.listOf;
|
||||
import static org.openmetadata.schema.api.teams.CreateUser.CreatePasswordType.ADMIN_CREATE;
|
||||
@ -130,8 +131,10 @@ import org.openmetadata.service.secrets.SecretsManagerFactory;
|
||||
import org.openmetadata.service.secrets.masker.EntityMaskerFactory;
|
||||
import org.openmetadata.service.security.AuthorizationException;
|
||||
import org.openmetadata.service.security.Authorizer;
|
||||
import org.openmetadata.service.security.CatalogPrincipal;
|
||||
import org.openmetadata.service.security.auth.AuthenticatorHandler;
|
||||
import org.openmetadata.service.security.auth.BotTokenCache;
|
||||
import org.openmetadata.service.security.auth.CatalogSecurityContext;
|
||||
import org.openmetadata.service.security.auth.UserTokenCache;
|
||||
import org.openmetadata.service.security.jwt.JWTTokenGenerator;
|
||||
import org.openmetadata.service.security.mask.PIIMasker;
|
||||
@ -168,6 +171,7 @@ public class UserResource extends EntityResource<User, UserRepository> {
|
||||
private AuthenticationConfiguration authenticationConfiguration;
|
||||
private AuthorizerConfiguration authorizerConfiguration;
|
||||
private final AuthenticatorHandler authHandler;
|
||||
private boolean isSelfSignUpEnabled = false;
|
||||
static final String FIELDS = "profile,roles,teams,follows,owns,domain,personas,defaultPersona";
|
||||
|
||||
@Override
|
||||
@ -205,6 +209,7 @@ public class UserResource extends EntityResource<User, UserRepository> {
|
||||
SmtpSettings smtpSettings = config.getSmtpSettings();
|
||||
this.isEmailServiceEnabled = smtpSettings != null && smtpSettings.getEnableSmtpServer();
|
||||
this.repository.initializeUsers(config);
|
||||
this.isSelfSignUpEnabled = authenticationConfiguration.getEnableSelfSignup();
|
||||
}
|
||||
|
||||
public static class UserList extends ResultList<User> {
|
||||
@ -430,15 +435,17 @@ public class UserResource extends EntityResource<User, UserRepository> {
|
||||
schema = @Schema(type = "string", example = FIELDS))
|
||||
@QueryParam("fields")
|
||||
String fieldsParam) {
|
||||
CatalogSecurityContext catalogSecurityContext =
|
||||
(CatalogSecurityContext) containerRequestContext.getSecurityContext();
|
||||
Fields fields = getFields(fieldsParam);
|
||||
String currentUserName = securityContext.getUserPrincipal().getName();
|
||||
User user = repository.getByName(uriInfo, currentUserName, fields);
|
||||
String currentEmail = ((CatalogPrincipal) catalogSecurityContext.getUserPrincipal()).getEmail();
|
||||
User user = repository.getByEmail(uriInfo, currentEmail, fields);
|
||||
|
||||
// Sync the Roles from token to User
|
||||
if (Boolean.TRUE.equals(authorizerConfiguration.getUseRolesFromProvider())
|
||||
&& Boolean.FALSE.equals(user.getIsBot() != null && user.getIsBot())) {
|
||||
reSyncUserRolesFromToken(
|
||||
uriInfo, user, getRolesFromAuthorizationToken(containerRequestContext));
|
||||
uriInfo, user, getRolesFromAuthorizationToken(catalogSecurityContext));
|
||||
}
|
||||
return addHref(uriInfo, user);
|
||||
}
|
||||
@ -463,9 +470,13 @@ public class UserResource extends EntityResource<User, UserRepository> {
|
||||
@ApiResponse(responseCode = "404", description = "User not found")
|
||||
})
|
||||
public List<EntityReference> getCurrentLoggedInUser(
|
||||
@Context UriInfo uriInfo, @Context SecurityContext securityContext) {
|
||||
String currentUserName = securityContext.getUserPrincipal().getName();
|
||||
return repository.getGroupTeams(uriInfo, currentUserName);
|
||||
@Context UriInfo uriInfo,
|
||||
@Context SecurityContext securityContext,
|
||||
@Context ContainerRequestContext containerRequestContext) {
|
||||
CatalogSecurityContext catalogSecurityContext =
|
||||
(CatalogSecurityContext) containerRequestContext.getSecurityContext();
|
||||
String currentEmail = ((CatalogPrincipal) catalogSecurityContext.getUserPrincipal()).getEmail();
|
||||
return repository.getGroupTeams(uriInfo, currentEmail);
|
||||
}
|
||||
|
||||
@POST
|
||||
@ -554,7 +565,9 @@ public class UserResource extends EntityResource<User, UserRepository> {
|
||||
|
||||
//
|
||||
try {
|
||||
validateAndAddUserAuthForBasic(user, create);
|
||||
// Email Validation
|
||||
validateEmailAlreadyExists(create.getEmail());
|
||||
addUserAuthForBasic(user, create);
|
||||
} catch (RuntimeException ex) {
|
||||
return Response.status(CONFLICT)
|
||||
.type(MediaType.APPLICATION_JSON_TYPE)
|
||||
@ -567,14 +580,26 @@ public class UserResource extends EntityResource<User, UserRepository> {
|
||||
// Add the roles on user creation
|
||||
updateUserRolesIfRequired(user, containerRequestContext);
|
||||
|
||||
Response createdUserRes = null;
|
||||
Response createdUserRes;
|
||||
try {
|
||||
createdUserRes = create(uriInfo, securityContext, user);
|
||||
} catch (EntityNotFoundException ex) {
|
||||
if (securityContext.getUserPrincipal().getName().equals(create.getName())) {
|
||||
// User is creating himself on signup ?! :(
|
||||
User created = addHref(uriInfo, repository.create(uriInfo, user));
|
||||
createdUserRes = Response.created(created.getHref()).entity(created).build();
|
||||
if (isSelfSignUpEnabled) {
|
||||
if (securityContext.getUserPrincipal().getName().equals(create.getName())) {
|
||||
// User is creating himself on signup ?! :(
|
||||
User created = addHref(uriInfo, repository.create(uriInfo, user));
|
||||
createdUserRes = Response.created(created.getHref()).entity(created).build();
|
||||
} else {
|
||||
throw new CustomExceptionMessage(
|
||||
FORBIDDEN,
|
||||
CatalogExceptionMessage.OTHER_USER_SIGN_UP_ERROR,
|
||||
CatalogExceptionMessage.OTHER_USER_SIGN_UP);
|
||||
}
|
||||
} else {
|
||||
throw new CustomExceptionMessage(
|
||||
FORBIDDEN,
|
||||
CatalogExceptionMessage.SELF_SIGNUP_NOT_ENABLED,
|
||||
CatalogExceptionMessage.SELF_SIGNUP_DISABLED_MESSAGE);
|
||||
}
|
||||
}
|
||||
|
||||
@ -589,26 +614,23 @@ public class UserResource extends EntityResource<User, UserRepository> {
|
||||
return Response.status(BAD_REQUEST).entity("User Cannot be created Successfully.").build();
|
||||
}
|
||||
|
||||
private void validateAndAddUserAuthForBasic(User user, CreateUser create) {
|
||||
private void addUserAuthForBasic(User user, CreateUser create) {
|
||||
if (isBasicAuth()) {
|
||||
// basic auth doesn't allow duplicate emails, since username part of the email is used as
|
||||
// login name
|
||||
validateEmailAlreadyExists(create.getEmail());
|
||||
user.setName(user.getEmail().split("@")[0]);
|
||||
if (Boolean.FALSE.equals(create.getIsBot())
|
||||
&& create.getCreatePasswordType() == ADMIN_CREATE) {
|
||||
addAuthMechanismToUser(user, create);
|
||||
}
|
||||
// else the user will get a mail if configured smtp
|
||||
}
|
||||
}
|
||||
|
||||
private void updateUserRolesIfRequired(
|
||||
User user, ContainerRequestContext containerRequestContext) {
|
||||
CatalogSecurityContext catalogSecurityContext =
|
||||
(CatalogSecurityContext) containerRequestContext.getSecurityContext();
|
||||
if (Boolean.TRUE.equals(authorizerConfiguration.getUseRolesFromProvider())
|
||||
&& Boolean.FALSE.equals(user.getIsBot() != null && user.getIsBot())) {
|
||||
user.setRoles(
|
||||
validateAndGetRolesRef(getRolesFromAuthorizationToken(containerRequestContext)));
|
||||
user.setRoles(validateAndGetRolesRef(getRolesFromAuthorizationToken(catalogSecurityContext)));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -46,9 +46,10 @@ public class CatalogOpenIdAuthorizationRequestFilter implements ContainerRequest
|
||||
return;
|
||||
}
|
||||
MultivaluedMap<String, String> headers = containerRequestContext.getHeaders();
|
||||
String principal = extractAuthorizedUserName(headers);
|
||||
String email = extractAuthorizedEmail(headers);
|
||||
String principal = extractAuthorizedUserName(email);
|
||||
LOG.debug("AuthorizedUserName:{}", principal);
|
||||
CatalogPrincipal catalogPrincipal = new CatalogPrincipal(principal);
|
||||
CatalogPrincipal catalogPrincipal = new CatalogPrincipal(principal, email);
|
||||
String scheme = containerRequestContext.getUriInfo().getRequestUri().getScheme();
|
||||
CatalogSecurityContext catalogSecurityContext =
|
||||
new CatalogSecurityContext(
|
||||
@ -62,14 +63,17 @@ public class CatalogOpenIdAuthorizationRequestFilter implements ContainerRequest
|
||||
return uriInfo.getPath().equalsIgnoreCase(HEALTH_END_POINT);
|
||||
}
|
||||
|
||||
protected String extractAuthorizedUserName(MultivaluedMap<String, String> headers) {
|
||||
LOG.debug("Request Headers:{}", headers);
|
||||
protected String extractAuthorizedUserName(String openIdEmail) {
|
||||
String[] openIdEmailParts = openIdEmail.split("@");
|
||||
return openIdEmailParts[0];
|
||||
}
|
||||
|
||||
protected String extractAuthorizedEmail(MultivaluedMap<String, String> headers) {
|
||||
LOG.debug("Request Headers:{}", headers);
|
||||
String openIdEmail = headers.getFirst(X_AUTH_PARAMS_EMAIL_HEADER);
|
||||
if (nullOrEmpty(openIdEmail)) {
|
||||
throw new AuthenticationException("Not authorized; User's Email is not present");
|
||||
}
|
||||
String[] openIdEmailParts = openIdEmail.split("@");
|
||||
return openIdEmailParts[0];
|
||||
return openIdEmail;
|
||||
}
|
||||
}
|
||||
|
@ -16,12 +16,16 @@ package org.openmetadata.service.security;
|
||||
import java.security.Principal;
|
||||
import lombok.Getter;
|
||||
|
||||
public record CatalogPrincipal(@Getter String name) implements Principal {
|
||||
public record CatalogPrincipal(@Getter String name, @Getter String email) implements Principal {
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "CatalogPrincipal{name='" + name + '\'' + '}';
|
||||
|
@ -15,6 +15,7 @@ package org.openmetadata.service.security;
|
||||
|
||||
import static org.openmetadata.common.utils.CommonUtil.listOrEmpty;
|
||||
import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty;
|
||||
import static org.openmetadata.service.security.SecurityUtil.findEmailFromClaims;
|
||||
import static org.openmetadata.service.security.SecurityUtil.findUserNameFromClaims;
|
||||
import static org.openmetadata.service.security.SecurityUtil.isBot;
|
||||
import static org.openmetadata.service.security.SecurityUtil.validateDomainEnforcement;
|
||||
@ -151,12 +152,14 @@ public class JwtFilter implements ContainerRequestFilter {
|
||||
|
||||
Map<String, Claim> claims = validateJwtAndGetClaims(tokenFromHeader);
|
||||
String userName = findUserNameFromClaims(jwtPrincipalClaimsMapping, jwtPrincipalClaims, claims);
|
||||
String email =
|
||||
findEmailFromClaims(jwtPrincipalClaimsMapping, jwtPrincipalClaims, claims, principalDomain);
|
||||
|
||||
// Check Validations
|
||||
checkValidationsForToken(claims, tokenFromHeader, userName);
|
||||
|
||||
// Setting Security Context
|
||||
CatalogPrincipal catalogPrincipal = new CatalogPrincipal(userName);
|
||||
CatalogPrincipal catalogPrincipal = new CatalogPrincipal(userName, email);
|
||||
String scheme = requestContext.getUriInfo().getRequestUri().getScheme();
|
||||
CatalogSecurityContext catalogSecurityContext =
|
||||
new CatalogSecurityContext(
|
||||
|
@ -33,7 +33,8 @@ public class NoopFilter implements ContainerRequestFilter {
|
||||
AuthorizerConfiguration authorizerConfiguration) {}
|
||||
|
||||
public void filter(ContainerRequestContext containerRequestContext) {
|
||||
CatalogPrincipal catalogPrincipal = new CatalogPrincipal("anonymous");
|
||||
CatalogPrincipal catalogPrincipal =
|
||||
new CatalogPrincipal("anonymous", "anonymous@openmetadata.org");
|
||||
String scheme = containerRequestContext.getUriInfo().getRequestUri().getScheme();
|
||||
CatalogSecurityContext catalogSecurityContext =
|
||||
new CatalogSecurityContext(
|
||||
|
@ -32,7 +32,7 @@ import static org.openmetadata.service.exception.CatalogExceptionMessage.INVALID
|
||||
import static org.openmetadata.service.exception.CatalogExceptionMessage.INVALID_USER_OR_PASSWORD;
|
||||
import static org.openmetadata.service.exception.CatalogExceptionMessage.MAX_FAILED_LOGIN_ATTEMPT;
|
||||
import static org.openmetadata.service.exception.CatalogExceptionMessage.PASSWORD_RESET_TOKEN_EXPIRED;
|
||||
import static org.openmetadata.service.exception.CatalogExceptionMessage.SELF_SIGNUP_ERROR;
|
||||
import static org.openmetadata.service.exception.CatalogExceptionMessage.SELF_SIGNUP_DISABLED_MESSAGE;
|
||||
import static org.openmetadata.service.exception.CatalogExceptionMessage.SELF_SIGNUP_NOT_ENABLED;
|
||||
import static org.openmetadata.service.exception.CatalogExceptionMessage.TOKEN_EXPIRED;
|
||||
import static org.openmetadata.service.exception.CatalogExceptionMessage.TOKEN_EXPIRY_ERROR;
|
||||
@ -136,7 +136,8 @@ public class BasicAuthenticator implements AuthenticatorHandler {
|
||||
registeredUser.setAuthenticationMechanism(null);
|
||||
return registeredUser;
|
||||
} else {
|
||||
throw new CustomExceptionMessage(NOT_IMPLEMENTED, SELF_SIGNUP_NOT_ENABLED, SELF_SIGNUP_ERROR);
|
||||
throw new CustomExceptionMessage(
|
||||
NOT_IMPLEMENTED, SELF_SIGNUP_NOT_ENABLED, SELF_SIGNUP_DISABLED_MESSAGE);
|
||||
}
|
||||
}
|
||||
|
||||
@ -523,7 +524,7 @@ public class BasicAuthenticator implements AuthenticatorHandler {
|
||||
|
||||
@Override
|
||||
public User lookUserInProvider(String userName) {
|
||||
User storedUser;
|
||||
User storedUser = null;
|
||||
try {
|
||||
if (userName.contains("@")) {
|
||||
// lookup by User Email
|
||||
@ -533,23 +534,16 @@ public class BasicAuthenticator implements AuthenticatorHandler {
|
||||
userName,
|
||||
new EntityUtil.Fields(
|
||||
Set.of(USER_PROTECTED_FIELDS, "roles"), "authenticationMechanism,roles"));
|
||||
} else {
|
||||
storedUser =
|
||||
userRepository.getByName(
|
||||
null,
|
||||
userName,
|
||||
new EntityUtil.Fields(
|
||||
Set.of(USER_PROTECTED_FIELDS, "roles"), "authenticationMechanism,roles"));
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
|
||||
if (storedUser != null && Boolean.TRUE.equals(storedUser.getIsBot())) {
|
||||
throw new CustomExceptionMessage(
|
||||
BAD_REQUEST, INVALID_USER_OR_PASSWORD, INVALID_USERNAME_PASSWORD);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
|
||||
if (storedUser == null || Boolean.TRUE.equals(storedUser.getIsBot())) {
|
||||
throw new CustomExceptionMessage(
|
||||
BAD_REQUEST, INVALID_USER_OR_PASSWORD, INVALID_USERNAME_PASSWORD);
|
||||
}
|
||||
|
||||
return storedUser;
|
||||
}
|
||||
}
|
||||
|
@ -30,7 +30,6 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.json.JsonPatch;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.core.UriInfo;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.openmetadata.schema.auth.BasicAuthMechanism;
|
||||
@ -271,9 +270,7 @@ public final class UserUtil {
|
||||
}
|
||||
|
||||
public static Set<String> getRolesFromAuthorizationToken(
|
||||
ContainerRequestContext containerRequestContext) {
|
||||
CatalogSecurityContext catalogSecurityContext =
|
||||
(CatalogSecurityContext) containerRequestContext.getSecurityContext();
|
||||
CatalogSecurityContext catalogSecurityContext) {
|
||||
return catalogSecurityContext.getUserRoles();
|
||||
}
|
||||
|
||||
|
@ -527,7 +527,7 @@ export const ENTITIES = {
|
||||
};
|
||||
|
||||
export const LOGIN = {
|
||||
username: 'admin',
|
||||
username: 'admin@openmetadata.org',
|
||||
password: 'admin',
|
||||
};
|
||||
|
||||
|
@ -11,7 +11,7 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
export const DEFAULT_ADMIN_USER = {
|
||||
userName: 'admin',
|
||||
userName: 'admin@openmetadata.org',
|
||||
password: 'admin',
|
||||
};
|
||||
|
||||
|
@ -359,43 +359,55 @@ export const AuthProvider = ({
|
||||
history.push(ROUTES.SIGNIN);
|
||||
};
|
||||
|
||||
const handleSuccessfulLogin = async (user: OidcUser) => {
|
||||
setApplicationLoading(true);
|
||||
setIsAuthenticated(true);
|
||||
const fields =
|
||||
authConfig?.provider === AuthProviderEnum.Basic
|
||||
? userAPIQueryFields + ',' + isEmailVerifyField
|
||||
: userAPIQueryFields;
|
||||
try {
|
||||
const res = await getLoggedInUser({ fields });
|
||||
if (res) {
|
||||
const updatedUserData = getUserDataFromOidc(res, user);
|
||||
if (!matchUserDetails(res, updatedUserData, ['email'])) {
|
||||
getUpdatedUser(updatedUserData, res);
|
||||
} else {
|
||||
setCurrentUser(res);
|
||||
}
|
||||
const handleSuccessfulLogin = useCallback(
|
||||
async (user: OidcUser) => {
|
||||
setApplicationLoading(true);
|
||||
setIsAuthenticated(true);
|
||||
const fields =
|
||||
authConfig?.provider === AuthProviderEnum.Basic
|
||||
? userAPIQueryFields + ',' + isEmailVerifyField
|
||||
: userAPIQueryFields;
|
||||
try {
|
||||
const res = await getLoggedInUser({ fields });
|
||||
if (res) {
|
||||
const updatedUserData = getUserDataFromOidc(res, user);
|
||||
if (!matchUserDetails(res, updatedUserData, ['email'])) {
|
||||
getUpdatedUser(updatedUserData, res);
|
||||
} else {
|
||||
setCurrentUser(res);
|
||||
}
|
||||
|
||||
handledVerifiedUser();
|
||||
// Start expiry timer on successful login
|
||||
startTokenExpiryTimer();
|
||||
handledVerifiedUser();
|
||||
// Start expiry timer on successful login
|
||||
startTokenExpiryTimer();
|
||||
}
|
||||
} catch (error) {
|
||||
const err = error as AxiosError;
|
||||
if (err?.response?.status === 404 && authConfig?.enableSelfSignup) {
|
||||
setNewUserProfile(user.profile);
|
||||
setCurrentUser({} as User);
|
||||
setIsSigningUp(true);
|
||||
history.push(ROUTES.SIGNUP);
|
||||
} else {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(err);
|
||||
showErrorToast(err);
|
||||
resetUserDetails();
|
||||
history.push(ROUTES.SIGNIN);
|
||||
}
|
||||
} finally {
|
||||
setApplicationLoading(false);
|
||||
}
|
||||
} catch (error) {
|
||||
const err = error as AxiosError;
|
||||
if (err && err.response && err.response.status === 404) {
|
||||
setNewUserProfile(user.profile);
|
||||
setCurrentUser({} as User);
|
||||
setIsSigningUp(true);
|
||||
history.push(ROUTES.SIGNUP);
|
||||
} else {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(err);
|
||||
history.push(ROUTES.SIGNIN);
|
||||
}
|
||||
} finally {
|
||||
setApplicationLoading(false);
|
||||
}
|
||||
};
|
||||
},
|
||||
[
|
||||
authConfig?.enableSelfSignup,
|
||||
setIsSigningUp,
|
||||
setIsAuthenticated,
|
||||
setApplicationLoading,
|
||||
setCurrentUser,
|
||||
setNewUserProfile,
|
||||
]
|
||||
);
|
||||
|
||||
const handleSuccessfulLogout = () => {
|
||||
resetUserDetails();
|
||||
@ -697,6 +709,19 @@ export const AuthProvider = ({
|
||||
return cleanup;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setHelperFunctionsRef({
|
||||
onLoginHandler,
|
||||
onLogoutHandler,
|
||||
handleSuccessfulLogin,
|
||||
trySilentSignIn,
|
||||
handleFailedLogin,
|
||||
updateAxiosInterceptors: initializeAxiosInterceptors,
|
||||
});
|
||||
|
||||
return cleanup;
|
||||
}, [handleSuccessfulLogin]);
|
||||
|
||||
const isConfigLoading =
|
||||
!authConfig ||
|
||||
(authConfig.provider === AuthProviderEnum.Azure && !msalInstance);
|
||||
|
@ -29,6 +29,7 @@ import BrandImage from '../../components/common/BrandImage/BrandImage';
|
||||
import Loader from '../../components/common/Loader/Loader';
|
||||
import LoginButton from '../../components/common/LoginButton/LoginButton';
|
||||
import { ROUTES, VALIDATION_MESSAGES } from '../../constants/constants';
|
||||
import { EMAIL_REG_EX } from '../../constants/regex.constants';
|
||||
import { AuthProvider } from '../../generated/settings/settings';
|
||||
import { useApplicationStore } from '../../hooks/useApplicationStore';
|
||||
import './login.style.less';
|
||||
@ -176,22 +177,20 @@ const SignInPage = () => {
|
||||
onFinish={handleSubmit}>
|
||||
<Form.Item
|
||||
data-testid="email"
|
||||
label={
|
||||
isAuthProviderLDAP
|
||||
? t('label.email')
|
||||
: t('label.username-or-email')
|
||||
}
|
||||
label={t('label.email')}
|
||||
name="email"
|
||||
requiredMark={false}
|
||||
rules={[{ required: true }]}>
|
||||
<Input
|
||||
autoFocus
|
||||
placeholder={
|
||||
isAuthProviderLDAP
|
||||
? t('label.email')
|
||||
: t('label.username-or-email')
|
||||
}
|
||||
/>
|
||||
rules={[
|
||||
{ required: true },
|
||||
{
|
||||
pattern: EMAIL_REG_EX,
|
||||
type: 'email',
|
||||
message: t('message.field-text-is-invalid', {
|
||||
fieldText: t('label.email'),
|
||||
}),
|
||||
},
|
||||
]}>
|
||||
<Input autoFocus placeholder={t('label.email')} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
data-testid="password"
|
||||
|
@ -24,6 +24,7 @@ import {
|
||||
ROUTES,
|
||||
VALIDATION_MESSAGES,
|
||||
} from '../../constants/constants';
|
||||
import { ClientType } from '../../generated/configuration/authenticationConfiguration';
|
||||
import { EntityReference } from '../../generated/entity/type';
|
||||
import { useApplicationStore } from '../../hooks/useApplicationStore';
|
||||
import { createUser } from '../../rest/userAPI';
|
||||
@ -47,6 +48,7 @@ const SignUp = () => {
|
||||
authorizerConfig,
|
||||
updateCurrentUser,
|
||||
newUser,
|
||||
authConfig,
|
||||
} = useApplicationStore();
|
||||
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
@ -82,6 +84,32 @@ const SignUp = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const clientType = authConfig?.clientType ?? ClientType.Public;
|
||||
|
||||
const initialValues = useMemo(
|
||||
() => ({
|
||||
displayName: newUser?.name ?? '',
|
||||
...(clientType === ClientType.Public
|
||||
? getNameFromUserData(
|
||||
newUser as UserProfile,
|
||||
jwtPrincipalClaims,
|
||||
authorizerConfig?.principalDomain,
|
||||
jwtPrincipalClaimsMapping
|
||||
)
|
||||
: {
|
||||
name: newUser?.name ?? '',
|
||||
email: newUser?.email ?? '',
|
||||
}),
|
||||
}),
|
||||
[
|
||||
clientType,
|
||||
authorizerConfig?.principalDomain,
|
||||
jwtPrincipalClaims,
|
||||
jwtPrincipalClaimsMapping,
|
||||
newUser,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex-center w-full h-full">
|
||||
<Card className="p-x-md p-y-md w-500">
|
||||
@ -112,15 +140,7 @@ const SignUp = () => {
|
||||
|
||||
<Form
|
||||
data-testid="create-user-form"
|
||||
initialValues={{
|
||||
displayName: newUser?.name || '',
|
||||
...getNameFromUserData(
|
||||
newUser as UserProfile,
|
||||
jwtPrincipalClaims,
|
||||
authorizerConfig?.principalDomain,
|
||||
jwtPrincipalClaimsMapping
|
||||
),
|
||||
}}
|
||||
initialValues={initialValues}
|
||||
layout="vertical"
|
||||
validateMessages={VALIDATION_MESSAGES}
|
||||
onFinish={handleCreateNewUser}>
|
||||
|
@ -104,6 +104,7 @@ export const getAuthConfig = (
|
||||
pkce: true,
|
||||
provider,
|
||||
clientType,
|
||||
enableSelfSignup,
|
||||
};
|
||||
}
|
||||
|
||||
@ -119,6 +120,7 @@ export const getAuthConfig = (
|
||||
scope: 'openid email profile',
|
||||
responseType,
|
||||
clientType,
|
||||
enableSelfSignup,
|
||||
};
|
||||
}
|
||||
|
||||
@ -133,6 +135,7 @@ export const getAuthConfig = (
|
||||
scope: 'openid email profile',
|
||||
responseType,
|
||||
clientType,
|
||||
enableSelfSignup,
|
||||
};
|
||||
}
|
||||
|
||||
@ -143,6 +146,7 @@ export const getAuthConfig = (
|
||||
samlConfiguration,
|
||||
provider,
|
||||
clientType,
|
||||
enableSelfSignup,
|
||||
};
|
||||
}
|
||||
|
||||
@ -157,6 +161,7 @@ export const getAuthConfig = (
|
||||
scope: 'openid email profile',
|
||||
responseType: 'code',
|
||||
clientType,
|
||||
enableSelfSignup,
|
||||
};
|
||||
}
|
||||
|
||||
@ -168,6 +173,7 @@ export const getAuthConfig = (
|
||||
callbackUrl: redirectUri,
|
||||
provider,
|
||||
clientType,
|
||||
enableSelfSignup,
|
||||
};
|
||||
|
||||
break;
|
||||
@ -205,6 +211,7 @@ export const getAuthConfig = (
|
||||
},
|
||||
provider,
|
||||
clientType,
|
||||
enableSelfSignup,
|
||||
} as Configuration;
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user