• Assume the problem is raised here. How do we check the status of a user when using Cognito on an AEM site? We will conduct the process of building a full flow from the front-end site to the AWS side.
» HTL Component
...
<div data-sly-use.templates="core/wcm/components/commons/v1/templates.html"
...
data-editmode="${wcmmode.edit ? 'true' : ''}"
data-resource="${resource.path}"
data-api-key="${model.apiKey}"
...
» Sling Model Java
@Model(adaptables = SlingHttpServletRequest.class,
adapters = SampleModel.class,
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SampleModelImpl implements SampleModel {
private static final Logger LOGGER = LoggerFactory.getLogger(SampleModelImpl.class);
@OSGiService
private transient FlagtickIntegrationService flagtickIntegrationService;
@PostConstruct
protected void init() {}
@Override
public String getApiKey() {
return flagtickIntegrationService.getApiKey();
}
}
» Typescript
...
import commonUtils from '@utils/commonUtils';
private $component;
private apiKey!:string;
private selector = 'sample-one';
constructor(cmp: HTMLElement) {
super(cmp);
this.$component = $(cmp);
this.init();
}
private init(): void {
this.apiKey = this.$cmp.dataset.apiKey as string;
const resource = this.$cmp.dataset.resource as string;
const sampleEncrypt = commonUtils.encryptData(sampleValue, this.apiKey);
const sampleEncode = encodeURIComponent(sampleEncrypt);
const editMode = this.$component.data('editmode') as string;
const endpoint = `${resource}.${this.selector}.json?sample=${sampleEncode}`;
...
Note: Use the CryptoJs libraries and get the API key from the Sling Model by using the @OSGiService annotation. Encrypt and encode the key before requesting the AEM Sling Servlet.
» Rest APIs
...
import $ from 'jquery';
...
declare interface SampleResponse {
Username: string,
Userstatus: string
}
if (!editMode) {
$.get(endpoint)
.done((data: SampleResponse): any => {
this.requestRestAPI();
})
.catch((err): void => {
logger.error(err);
});
}
» Sling Servlet
@Component(immediate = true, service = Servlet.class,
property = {
SERVICE_DESCRIPTION + GetUserServlet.SERVLET_SERVICE_DESCRIPTION,
SLING_SERVLET_RESOURCE_TYPES + GetUserServlet.RESOURCE_TYPE,
SLING_SERVLET_METHODS + "=" + HttpConstants.METHOD_GET,
SLING_SERVLET_SELECTORS + GetUserServlet.SELECTOR,
SLING_SERVLET_EXTENSIONS + "=" + Constants.EXTENSION_JSON
})
public class GetUserServlet extends SlingSafeMethodsServlet {
public static final String SERVLET_SERVICE_DESCRIPTION = "<Your Description about the Servlet>";
public static final String RESOURCE_TYPE = "=flagtick/components/content/sample";
public static final String SELECTOR = "=sample-one";
private static final long serialVersionUID = 1L;
@Reference
transient private FlagtickIntegrationService flagtickIntegrationService;
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
if (promiseIntegrationService == null) {
response.setStatus(HTTP_UNAVAILABLE);
response.getWriter().write("Service unavailable");
return;
}
response.setContentType(Constants.CONTENT_TYPE_JSON);
response.setCharacterEncoding(Constants.ENCODING_UTF8);
response.setStatus(HTTP_OK);
Map<String, String> params = new HashMap<>();
params.put(Constants.USERNAME_PARAMETER, request.getParameter(Constants.USERNAME_PARAMETER));
CognitoUserModel cognitoUserModel = flagtickIntegrationService.verifyUserInCognito(params);
if (cognitoUserModel == null) {
response.setStatus(HTTP_BAD_REQUEST);
response.getWriter().write("Invalid request parameters");
return;
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(response.getWriter(), cognitoUserModel);
}
}
» DTO Java Class
public class CognitoUserModel {
/* Parsed Attributes */
private String Username;
private String Userstatus;
public CognitoUserModel(String username, String userstatus) {
this.Username = username;
this.Userstatus = userstatus;
}
public CognitoUserModel() {
/* Default Constructor */
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getUserstatus() {
return Userstatus;
}
public void setUserstatus(String userstatus) {
Userstatus = userstatus;
}
}
» Enable Lambda Proxy Integration
» Setup API key and URL Query String Parameters
» Validate Endpoint on Lambda
» Integrating adminGetUser
const AWS = require('aws-sdk');
const cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({ region: 'us-west-2' });
const commonUtils = require('./commonUtils.js');
var encryptionKey = '<Your Private Key>';
exports.handler = async (event) => {
if (!event.queryStringParameters || !event.queryStringParameters.username) {
return {
"statusCode": 400,
"body": "Invalid request parameters"
};
}
const usernameParam = event.queryStringParameters.username;
const UserNameDecode = decodeURIComponent(usernameParam);
const UserNameDecrypted = commonUtils.decryptData(UserNameDecode, encryptionKey);
const userParams = {
UserPoolId: '<Your User Pool ID>',
Username: userNameDecrypted
};
try {
const response = await cognitoIdentityServiceProvider.adminGetUser(userParams).promise();
const responseBody = {
Username: response.Username,
Userstatus: response.Enabled ? 'enabled' : 'disabled'
};
return {
statusCode: 200,
body: JSON.stringify(responseBody)
};
} catch (error) {
return {
"statusCode": 500,
"body": 'Something went wrong'
};
}
};