From 43d3bf2c6720ffe70c5c9fda39ffd092789a3472 Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Sun, 29 May 2022 07:48:17 +0530 Subject: [PATCH 01/22] Skeleton code for User Registration feature --- .../org/sunbird/common/util/Constants.java | 767 +++++++++--------- .../UserRegistrationController.java | 36 + .../registration/model/UserRegistration.java | 73 ++ .../model/UserRegistrationInfo.java | 73 ++ .../service/UserRegistrationConsumer.java | 31 + .../service/UserRegistrationService.java | 42 + .../service/UserRegistrationServiceImpl.java | 45 + .../util/UserRegistrationStatus.java | 22 + 8 files changed, 707 insertions(+), 382 deletions(-) create mode 100644 src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java create mode 100644 src/main/java/org/sunbird/user/registration/model/UserRegistration.java create mode 100644 src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java create mode 100644 src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java create mode 100644 src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java create mode 100644 src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java create mode 100644 src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java diff --git a/src/main/java/org/sunbird/common/util/Constants.java b/src/main/java/org/sunbird/common/util/Constants.java index e78c0b003..41e34eb9d 100644 --- a/src/main/java/org/sunbird/common/util/Constants.java +++ b/src/main/java/org/sunbird/common/util/Constants.java @@ -5,391 +5,394 @@ import java.util.List; public class Constants { - public static final String UUID = "wid"; - public static final String KID = "kid"; - public static final String SOURCE_ID = "source_id"; - public static final String FIRST_NAME = "first_name"; - public static final String LAST_NAME = "last_name"; - public static final String MIDDLE_NAME = "middle_name"; - public static final String FIRSTNAME = "firstName"; - public static final String LASTNAME = "lastName"; - public static final String CONTACT_PHONE_NUMBER_OFFICE = "contact_phone_number_office"; - public static final String CONTACT_PHONE_NUMBER_HOME = "contact_phone_number_home"; - public static final String CONTACT_PHONE_NUMBER_PERSONAL = "contact_phone_number_personal"; - public static final String KNOWN_AS = "known_as"; - public static final String GENDER = "gender"; - public static final String DOB = "dob"; - public static final String SALUTATION = "salutation"; - public static final String EMAIL = "email"; - public static final String PROFILE_DETAILS_KEY = "profiledetails"; - public static final String SOURCE_PROFILE_PICTURE = "source_profile_picture"; - public static final String ROOT_ORG = "root_org"; - public static final String ORG = "org"; - public static final String EMPLOYEMENT_STATUS = "employement_status"; - public static final String CONTRACT_TYPE = "contract_type"; - public static final String JOB_TITLE = "job_title"; - public static final String JOB_ROLE = "job_role"; - public static final String DEPARTMENT_NAME = "department_name"; - public static final String UNIT_NAME = "unit_name"; - public static final String LANGUAGES_KNOWN = "languages_known"; - public static final String ORGANIZATION_LOCATION_COUNTRY = "organization_location_country"; - public static final String ORGANIZATION_LOCATION_STATE = "organization_location_state"; - public static final String ORGANIZATION_LOCATION_CITY = "organization_location_city"; - public static final String RESIDENCE_COUNTRY = "residence_country"; - public static final String RESIDENCE_STATE = "residence_state"; - public static final String RESIDENCE_CITY = "residence_city"; - public static final String TIME_INSERTED = "time_inserted"; - public static final String TIME_UPDATED = "time_updated"; - public static final String JSON_UNMAPPED_FIELDS = "json_unmapped_fields"; - public static final String IS_ACTIVE = "is_active"; - public static final String ACCOUNT_EXPIRY_DATE = "account_expiry_date"; - public static final String SOURCE_DATA = "source_data"; - public static final String USER_ID = "userId"; - public static final String FILTERS = "filters"; - public static final String CONTENT_ID = "content_id"; - public static final String BATCH_ID = "batchId"; - public static final String COURSE_ID = "courseId"; - public static final String ENROLMENT_TYPE = "enrollmenttype"; - public static final String IDENTIFIER = "identifier"; - public static final String START_DATE = "startDate"; - public static final String END_DATE = "endDate"; - public static final String ACTIVE = "active"; - public static final String COMPLETION_PERCENTAGE = "completionPercentage"; - public static final String PROGRESS = "progress"; - public static final String PROFILEDETAILS = "profiledetails"; - public static final String EMPLOYMENTDETAILS = "employmentDetails"; - public static final String DEPARTMENTNAME = "departmentName"; - public static final String ISSUED_CERTIFICATES = "issued_certificates"; - public static final String IS_MDO = "isMdo"; - public static final String IS_CBP = "isCbp"; - public static final String PROFILE_DETAILS_DESIGNATION = "profileDetails.professionalDetails.designation"; - public static final String PROFILE_DETAILS_DESIGNATION_OTHER = "profileDetails.professionalDetails.designationOther"; - public static final String PROFILE_DETAILS_PRIMARY_EMAIL = "profileDetails.personalDetails.primaryEmail"; - public static final String DEPARTMENT = "department"; - public static final String DESIGNATION = "designation"; - public static final String PRIMARY_EMAIL = "primaryEmail"; - public static final String FIRST_LOGIN_TIME = "firstLoginTime"; - public static final String RESPONSE_CODE = "responseCode"; - public static final String AUTH_TOKEN = "Authorization"; - public static final String X_AUTH_TOKEN = "x-authenticated-user-token"; - public static final String SUCCESSFUL = "Successful"; - public static final String FAILED = "Failed"; - public static final String MESSAGE = "message"; - public static final String DATA = "data"; - public static final String STATUS = "status"; - public static final String RESULT = "result"; - public static final String OK = "OK"; - public static final String ADD = "add"; - public static final String UPDATE = "update"; - public static final String CREATE = "create"; - public static final String ROOT_ORG_CONSTANT = "rootOrg"; - public static final String ORG_CONSTANT = "org"; - public static final String USER_ID_CONSTANT = "userId"; - public static final String FIELD_PASSED_CONSTANT = "fieldsPassed"; - public static final String FETCH_ONE_LEVEL_CONSTANT = "fetchOneLevel"; - public static final String SKIP_ACCESS_CHECK_CONSTANT = "skipAccessCheck"; - public static final String FIELDS_CONSTANT = "fields"; - public static final boolean FIELDS_PASSED = true; - public static final boolean FETCH_ON_LEVEL = false; - public static final boolean SKIP_ACCESS_CHECK = true; - public static final List MINIMUL_FIELDS = Collections - .unmodifiableList(Arrays.asList("identifier", "duration", "downloadUrl", "description", "mimeType", - "artifactUrl", "name", STATUS, "resourceType", "categoryType", "category")); - public static final String FETCH_RESULT_CONSTANT = ".fetchResult:"; - public static final String URI_CONSTANT = "URI: "; - public static final String REQUEST_CONSTANT = "Request: "; - public static final String RESPONSE_CONSTANT = "Response: "; - public static final String SERVICE_ERROR_CONSTANT = "Http Client threw an Exception:"; - public static final String EXTERNAL_SERVICE_ERROR_CODE = "Exception while querying the external service:"; - public static final String CONTENT_ID_REPLACER = "{contentId}"; - // User assessment pass mark - public static final Float ASSESSMENT_PASS_SCORE = 60.0f; - public static final String DATE_FORMAT = "yyyy-mm-dd hh:mm:ss"; - public static final String RESPONSE = "response"; - public static final String STAFF = "staff"; - public static final String API_STAFF_POSITION_ADD = "api.staff.position.add"; - public static final String API_STAFF_POSITION_UPDATE = "api.staff.position.update"; - public static final String API_STAFF_POSITION_READ = "api.staff.position.read"; - public static final String API_STAFF_POSITION_DELETE = "api.staff.position.delete"; - public static final String API_STAFF_POSITION_HISTORY_READ = "api.staff.position.history.read"; - public static final String API_BUDGET_SCHEME_ADD = "api.budget.schme.add"; - public static final String API_BUDGET_SCHEME_DOC_ADD = "api.budget.schme.doc.add"; - public static final String API_BUDGET_SCHEME_UPDATE = "api.budget.schme.update"; - public static final String API_BUDGET_SCHEME_READ = "api.budget.scheme.read"; - public static final String API_BUDGET_SCHEME_DELETE = "api.budget.scheme.delete"; - public static final String API_BUDGET_SCHEME_HISTORY_READ = "api.budget.scheme.history.read"; - public static final String API_FILE_UPLOAD = "api.file.upload"; - public static final String API_FILE_DELETE = "api.file.delete"; - public static final String API_PROFILE_UPDATE = "api.profile.update"; - public static final String ID = "id"; - public static final String ORG_ID = "orgId"; - public static final String POSITION = "position"; - public static final String TOTAL_POSITION_FILLED = "totalPositionsFilled"; - public static final String TOTAL_POSITION_VACANT = "totalPositionsVacant"; - public static final String NAME = "name"; - public static final String URL = "url"; - public static final String DELETED = "deleted"; - public static final String SCHEME_ID = "schemeId"; - public static final String BUDGET = "budget"; - public static final String BUDGET_YEAR = "budgetYear"; - public static final String SCHEME_NAME = "schemeName"; - public static final String SALARY_BUDGET_ALLOCATED = "salaryBudgetAllocated"; - public static final String TRAINING_BUDGET_ALLOCATED = "trainingBudgetAllocated"; - public static final String TRAINING_BUDGET_UTILIZATION = "trainingBudgetUtilization"; + public static final String UUID = "wid"; + public static final String KID = "kid"; + public static final String SOURCE_ID = "source_id"; + public static final String FIRST_NAME = "first_name"; + public static final String LAST_NAME = "last_name"; + public static final String MIDDLE_NAME = "middle_name"; + public static final String FIRSTNAME = "firstName"; + public static final String LASTNAME = "lastName"; + public static final String CONTACT_PHONE_NUMBER_OFFICE = "contact_phone_number_office"; + public static final String CONTACT_PHONE_NUMBER_HOME = "contact_phone_number_home"; + public static final String CONTACT_PHONE_NUMBER_PERSONAL = "contact_phone_number_personal"; + public static final String KNOWN_AS = "known_as"; + public static final String GENDER = "gender"; + public static final String DOB = "dob"; + public static final String SALUTATION = "salutation"; + public static final String EMAIL = "email"; + public static final String PROFILE_DETAILS_KEY = "profiledetails"; + public static final String SOURCE_PROFILE_PICTURE = "source_profile_picture"; + public static final String ROOT_ORG = "root_org"; + public static final String ORG = "org"; + public static final String EMPLOYEMENT_STATUS = "employement_status"; + public static final String CONTRACT_TYPE = "contract_type"; + public static final String JOB_TITLE = "job_title"; + public static final String JOB_ROLE = "job_role"; + public static final String DEPARTMENT_NAME = "department_name"; + public static final String UNIT_NAME = "unit_name"; + public static final String LANGUAGES_KNOWN = "languages_known"; + public static final String ORGANIZATION_LOCATION_COUNTRY = "organization_location_country"; + public static final String ORGANIZATION_LOCATION_STATE = "organization_location_state"; + public static final String ORGANIZATION_LOCATION_CITY = "organization_location_city"; + public static final String RESIDENCE_COUNTRY = "residence_country"; + public static final String RESIDENCE_STATE = "residence_state"; + public static final String RESIDENCE_CITY = "residence_city"; + public static final String TIME_INSERTED = "time_inserted"; + public static final String TIME_UPDATED = "time_updated"; + public static final String JSON_UNMAPPED_FIELDS = "json_unmapped_fields"; + public static final String IS_ACTIVE = "is_active"; + public static final String ACCOUNT_EXPIRY_DATE = "account_expiry_date"; + public static final String SOURCE_DATA = "source_data"; + public static final String USER_ID = "userId"; + public static final String FILTERS = "filters"; + public static final String CONTENT_ID = "content_id"; + public static final String BATCH_ID = "batchId"; + public static final String COURSE_ID = "courseId"; + public static final String ENROLMENT_TYPE = "enrollmenttype"; + public static final String IDENTIFIER = "identifier"; + public static final String START_DATE = "startDate"; + public static final String END_DATE = "endDate"; + public static final String ACTIVE = "active"; + public static final String COMPLETION_PERCENTAGE = "completionPercentage"; + public static final String PROGRESS = "progress"; + public static final String PROFILEDETAILS = "profiledetails"; + public static final String EMPLOYMENTDETAILS = "employmentDetails"; + public static final String DEPARTMENTNAME = "departmentName"; + public static final String ISSUED_CERTIFICATES = "issued_certificates"; + public static final String IS_MDO = "isMdo"; + public static final String IS_CBP = "isCbp"; + public static final String PROFILE_DETAILS_DESIGNATION = "profileDetails.professionalDetails.designation"; + public static final String PROFILE_DETAILS_DESIGNATION_OTHER = "profileDetails.professionalDetails.designationOther"; + public static final String PROFILE_DETAILS_PRIMARY_EMAIL = "profileDetails.personalDetails.primaryEmail"; + public static final String DEPARTMENT = "department"; + public static final String DESIGNATION = "designation"; + public static final String PRIMARY_EMAIL = "primaryEmail"; + public static final String FIRST_LOGIN_TIME = "firstLoginTime"; + public static final String RESPONSE_CODE = "responseCode"; + public static final String AUTH_TOKEN = "Authorization"; + public static final String X_AUTH_TOKEN = "x-authenticated-user-token"; + public static final String SUCCESSFUL = "Successful"; + public static final String FAILED = "Failed"; + public static final String MESSAGE = "message"; + public static final String DATA = "data"; + public static final String STATUS = "status"; + public static final String RESULT = "result"; + public static final String OK = "OK"; + public static final String ADD = "add"; + public static final String UPDATE = "update"; + public static final String CREATE = "create"; + public static final String ROOT_ORG_CONSTANT = "rootOrg"; + public static final String ORG_CONSTANT = "org"; + public static final String USER_ID_CONSTANT = "userId"; + public static final String FIELD_PASSED_CONSTANT = "fieldsPassed"; + public static final String FETCH_ONE_LEVEL_CONSTANT = "fetchOneLevel"; + public static final String SKIP_ACCESS_CHECK_CONSTANT = "skipAccessCheck"; + public static final String FIELDS_CONSTANT = "fields"; + public static final boolean FIELDS_PASSED = true; + public static final boolean FETCH_ON_LEVEL = false; + public static final boolean SKIP_ACCESS_CHECK = true; + public static final List MINIMUL_FIELDS = Collections + .unmodifiableList(Arrays.asList("identifier", "duration", "downloadUrl", "description", "mimeType", + "artifactUrl", "name", STATUS, "resourceType", "categoryType", "category")); + public static final String FETCH_RESULT_CONSTANT = ".fetchResult:"; + public static final String URI_CONSTANT = "URI: "; + public static final String REQUEST_CONSTANT = "Request: "; + public static final String RESPONSE_CONSTANT = "Response: "; + public static final String SERVICE_ERROR_CONSTANT = "Http Client threw an Exception:"; + public static final String EXTERNAL_SERVICE_ERROR_CODE = "Exception while querying the external service:"; + public static final String CONTENT_ID_REPLACER = "{contentId}"; + // User assessment pass mark + public static final Float ASSESSMENT_PASS_SCORE = 60.0f; + public static final String DATE_FORMAT = "yyyy-mm-dd hh:mm:ss"; + public static final String RESPONSE = "response"; + public static final String STAFF = "staff"; + public static final String API_STAFF_POSITION_ADD = "api.staff.position.add"; + public static final String API_STAFF_POSITION_UPDATE = "api.staff.position.update"; + public static final String API_STAFF_POSITION_READ = "api.staff.position.read"; + public static final String API_STAFF_POSITION_DELETE = "api.staff.position.delete"; + public static final String API_STAFF_POSITION_HISTORY_READ = "api.staff.position.history.read"; + public static final String API_BUDGET_SCHEME_ADD = "api.budget.schme.add"; + public static final String API_BUDGET_SCHEME_DOC_ADD = "api.budget.schme.doc.add"; + public static final String API_BUDGET_SCHEME_UPDATE = "api.budget.schme.update"; + public static final String API_BUDGET_SCHEME_READ = "api.budget.scheme.read"; + public static final String API_BUDGET_SCHEME_DELETE = "api.budget.scheme.delete"; + public static final String API_BUDGET_SCHEME_HISTORY_READ = "api.budget.scheme.history.read"; + public static final String API_FILE_UPLOAD = "api.file.upload"; + public static final String API_FILE_DELETE = "api.file.delete"; + public static final String API_PROFILE_UPDATE = "api.profile.update"; + public static final String ID = "id"; + public static final String ORG_ID = "orgId"; + public static final String POSITION = "position"; + public static final String TOTAL_POSITION_FILLED = "totalPositionsFilled"; + public static final String TOTAL_POSITION_VACANT = "totalPositionsVacant"; + public static final String NAME = "name"; + public static final String URL = "url"; + public static final String DELETED = "deleted"; + public static final String SCHEME_ID = "schemeId"; + public static final String BUDGET = "budget"; + public static final String BUDGET_YEAR = "budgetYear"; + public static final String SCHEME_NAME = "schemeName"; + public static final String SALARY_BUDGET_ALLOCATED = "salaryBudgetAllocated"; + public static final String TRAINING_BUDGET_ALLOCATED = "trainingBudgetAllocated"; + public static final String TRAINING_BUDGET_UTILIZATION = "trainingBudgetUtilization"; + // ratings and review + public static final String API_RATINGS_ADD = "api.ratings.add"; + public static final String API_RATINGS_READ = "api.ratings.read"; + public static final String API_RATINGS_UPDATE = "api.ratings.update"; + public static final String API_RATINGS_SUMMARY = "api.ratings.summary"; + public static final String API_RATINGS_LOOKUP = "api.ratings.lookup"; + public static final String DATABASE = "sunbird"; + public static final String LOGIN_TABLE = "user_first_login_details"; + public static final String ACTIVITY_ID = "activityId"; + public static final String ACTIVITY_TYPE = "activityType"; + public static final String RATINGS_USER_ID = "userId"; + public static final String USER_FIRST_NAME = "firstName"; + public static final String USER_LAST_NAME = "lastName"; + public static final String USERID = "id"; + public static final String COMMENT = "comment"; + public static final String COMMENT_BY = "commentBy"; + public static final String COMMENT_UPDATED_ON = "commentupdatedon"; + public static final String CREATED_ON = "createdon"; + public static final String RATING = "rating"; + public static final String REVIEW = "review"; + public static final String UPDATED_ON = "updatedon"; + public static final String LATEST50REVIEWS = "latest50reviews"; + public static final String SUMMARY_ACTIVITY_ID = "activityid"; + public static final String SUMMARY_ACTIVITY_TYPE = "activitytype"; + public static final String TOTALCOUNT1STARS = "totalcount1stars"; + public static final String TOTALCOUNT2STARS = "totalcount2stars"; + public static final String TOTALCOUNT3STARS = "totalcount3stars"; + public static final String TOTALCOUNT4STARS = "totalcount4stars"; + public static final String TOTALCOUNT5STARS = "totalcount5stars"; + public static final String TOTALNUMBEROFRATINGS = "total_number_of_ratings"; + public static final String SUMOFTOTALRATINGS = "sum_of_total_ratings"; + public static final String NO_RATING_EXCEPTION_MESSAGE = "No ratings found for : "; + public static final String NO_REVIEW_EXCEPTION_MESSAGE = "No reviews found for : "; + public static final String RATING_GENERIC_EXCEPTION_MESSAGE = "Exception occurred while adding the course review : "; + public static final String KAFKA_RATING_EXCEPTION_MESSAGE = "Exception occurred while connecting to kafka topic : "; + public static final String RATING_UPSERT_OPERATION = "upsert"; + public static final String RATING_LOOKUP_RATING_OPERATION = "lookup"; + public static final String RATING_GET_OPERATION = "getRating"; + public static final String RATING_SUMMARY_OPERATION = "getSummary"; + // assessment + public static final String QUESTION_SET = "questionSet"; + public static final String ASSESSMENT_QNS_ANS_SET = "assessmentQnsAnsSet_"; + public static final String ASSESSMENT_QNS_SET = "assessmentQnsSet_"; + // Cassandra Constants + public static final String INSERT_INTO = "INSERT INTO "; + public static final String DOT = "."; + public static final String OPEN_BRACE = "("; + public static final String VALUES_WITH_BRACE = ") VALUES ("; + public static final String QUE_MARK = "?"; + public static final String COMMA = ","; + public static final String CLOSING_BRACE = ");"; + public static final String SUCCESS = "success"; + public static final String UNKNOWN_IDENTIFIER = "Unknown identifier "; + public static final String UNDEFINED_IDENTIFIER = "Undefined column name "; + public static final String EXCEPTION_MSG_FETCH = "Exception occurred while fetching record from "; + public static final String EXCEPTION_MSG_DELETE = "Exception occurred while deleting record from "; + public static final String AUDIT_TYPE = "auditType"; + public static final String CREATED_DATE = "createdDate"; + public static final String CREATED_BY = "createdBy"; + public static final String UPDATED_DATE = "updatedDate"; + public static final String UPDATED_BY = "updatedBy"; + public static final String TRANSACTION_DETAILS = "transactionDetails"; + public static final String PROOF_DOCS = "proofDocs"; + public static final String WORK_ORDER_ID = "workOrderId"; + public static final String WORK_ALLOCATION_ID = "workAllocationId"; + public static final String BEGIN_BATCH = "BEGIN BATCH "; + public static final String APPLY_BATCH = " APPLY BATCH;"; + // Database and Tables + public static final String KEYSPACE_SUNBIRD = "sunbird"; + public static final String KEYSPACE_SUNBIRD_COURSES = "sunbird_courses"; + public static final String TABLE_ORG_BUDGET_SCHEME = "org_budget_scheme"; + public static final String TABLE_USER_ASSESSMENT_TIME = "user_assessment_time"; + public static final String SHA_256_WITH_RSA = "SHA256withRSA"; + public static final String SUB = "sub"; + public static final String _UNAUTHORIZED = "Unauthorized"; + public static final String DOT_SEPARATOR = "."; + public static final String ACCESS_TOKEN_PUBLICKEY_BASEPATH = "accesstoken.publickey.basepath"; + public static final String TABLE_ORG_AUDIT = "org_audit"; + public static final String TABLE_ORG_STAFF_POSITION = "org_staff_position"; + public static final String TABLE_WORK_ORDER = "work_order"; + public static final String TABLE_WORK_ALLOCATION = "work_allocation"; + public static final String TABLE_USER_WORK_ALLOCATION_MAPPING = "user_work_allocation_mapping"; + public static final String TABLE_MANDATORY_USER_CONTENT = "mandatory_user_content"; + public static final String TABLE_ORGANIZATION = "organisation"; + public static final String TABLE_USER_ENROLMENT = "user_enrolments"; + public static final String TABLE_USER = "user"; + public static final String TABLE_COURSE_BATCH = "course_batch"; + public static final String TABLE_RATINGS = "ratings"; + public static final String TABLE_RATINGS_LOOKUP = "ratings_lookup"; + public static final String TABLE_RATINGS_SUMMARY = "ratings_summary"; + public static final String VALUE = "value"; + public static final String DEPT_NAME = "deptName"; + public static final String PROFILE_DETAILS = "profileDetails"; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String APPLICATION_JSON = "application/json"; + public static final String OSID = "osid"; + public static final String INITIATE = "INITIATE"; + public static final String FIELD_KEY = "fieldKey"; + public static final String TO_VALUE = "toValue"; + public static final String FROM_VALUE = "fromValue"; + public static final String STATE = "state"; + public static final String ACTION = "action"; + public static final String APPLICATION_ID = "applicationId"; + public static final String ACTOR_USER_ID = "actorUserId"; + public static final String SERVICE_NAME = "serviceName"; + public static final String PROFILE = "profile"; + public static final String WFID = "wfId"; + public static final String UPDATE_FIELD_VALUES = "updateFieldValues"; + public static final String PROFILE_UPDATE_FIELDS = "profileUpdateFields_"; + public static final String IGOT = "igot"; + public static final String DOPT = "dopt"; + public static final String PERSONAL_DETAILS = "personalDetails"; + public static final String TRANSITION_DETAILS = "transitionDetails"; + public static final String UNAUTHORIZED = "unauthorized"; + // Redis + public static final String API_REDIS_DELETE = "api.redis.delete"; + public static final String API_REDIS_GET_KEYS = "api.redis.get.keys"; + public static final String API_REDIS_GET_KEYS_VALUE_SET = "api.redis.get.keys&values"; + public static final String REDIS_COMMON_KEY = "CB_EXT_"; + public static final String COMPETENCY_CACHE_NAME = "competency"; + public static final String COMPETENCY_CACHE_NAME_BY_AREA = "competencyByArea"; + public static final String COMPETENCY_CACHE_NAME_BY_TYPE = "competencyByType"; + public static final String PROVIDER_CACHE_NAME = "provider"; + public static final String COMPETENCY_FACET_NAME = "competencies_v3.name"; + public static final String IS_TENANT = "isTenant"; + public static final String CHANNEL = "channel"; + public static final String USER_TOKEN = "x-authenticated-user-token"; + public static final String AUTHORIZATION = "authorization"; + public static final String FACETS = "facets"; + public static final String PRIMARY_CATEGORY = "primaryCategory"; + public static final String LIMIT = "limit"; + public static final String REQUEST = "request"; + public static final String FIELDS = "fields"; + public static final String OFFSET = "offset"; + public static final String BUDGET_DOC_UPLOADED_BY = "uploadedBy"; + public static final String BUDGET_DOC_UPLOADED_DATE = "uploadedDate"; + public static final String BUDGET_DOC_FILE_NAME = "fileName"; + public static final String BUDGET_DOC_FILE_TYPE = "fileType"; + public static final String BUDGET_DOC_FILE_SIZE = "fileSize"; + public static final String BUDGET_DOC_FILE_URL = "fileUrl"; + // telemetry audit constants + public static final String ORG_LIST = "ORGANISATION_LIST"; + public static final String VERSION = "3.0.2"; + public static final String EID = "AUDIT"; + public static final String PDATA_ID = "dev.sunbird.cb.ext.service"; + public static final String PDATA_PID = "sunbird-cb-ext-service"; + public static final String TYPE = "WorkOrder"; + public static final String CURRENT_STATE = "FirstLogin"; + public static final String LOGIN_TIME = "login_time"; + public static final List PROPS = Collections.unmodifiableList(Arrays.asList("WAT")); + public static final String USER_CONST = "User"; + public static final String ASSESSMENT_LEVEL_SCORE_CUTOFF = "assessmentlevel"; + public static final String SECTION_LEVEL_SCORE_CUTOFF = "sectionlevel"; + public static final String IDENTIFIER_REPLACER = "{identifier}"; + public static final String CHILDREN = "children"; + public static final String PARAMS = "params"; + public static final String MAX_QUESTIONS = "maxQuestions"; + public static final String CHILD_NODES = "childNodes"; + public static final String SEARCH = "search"; + public static final String QUESTION_ID = "qs_id_"; + public static final String ASSESSMENT_ID = "assess_id_"; + public static final String EDITOR_STATE = "editorState"; + public static final String CHOICES = "choices"; + public static final String ANSWER = "answer"; + public static final String QUESTION = "question"; + public static final String OPTIONS = "options"; + public static final String USER_ASSESS_REQ = "user_assess_req_"; + public static final String HIERARCHY = "hierarchy"; + public static final String DEV_HIERARCHY_STORE = "dev_hierarchy_store"; + public static final String CONTENT_HIERARCHY = "content_hierarchy"; + public static final String BATCH_ID_ = "batchid"; + public static final String COURSE_ID_ = "courseid"; + public static final String COMPLETION_PERCENTAGE_ = "completionpercentage"; + public static final String LAST_ACCESS_TIME = "last_access_time"; + public static final String SUNBIRD_KEY_SPACE_NAME = "sunbird"; + public static final String SUNBIRD_COURSES_KEY_SPACE_NAME = "sunbird_courses"; + public static final String LAST_ACCESS_TIME_GAP = "last.access.time.gap.millis"; + public static final String USER_CONTENT_CONSUMPTION = "user_content_consumption"; + public static final String NOTIFICATION_UTIL = "notificationUtil"; + public static final String NOTIFICATIONS = "notifications"; + public static final String CORE_CONNECTIONS_PER_HOST_FOR_LOCAL = "coreConnectionsPerHostForLocal"; + public static final String CORE_CONNECTIONS_PER_HOST_FOR_REMOTE = "coreConnectionsPerHostForRemote"; + public static final String MAX_CONNECTIONS_PER_HOST_FOR_LOCAl = "maxConnectionsPerHostForLocal"; + public static final String MAX_CONNECTIONS_PER_HOST_FOR_REMOTE = "maxConnectionsPerHostForRemote"; + public static final String MAX_REQUEST_PER_CONNECTION = "maxRequestsPerConnection"; + public static final String HEARTBEAT_INTERVAL = "heartbeatIntervalSeconds"; + public static final String POOL_TIMEOUT = "poolTimeoutMillis"; + public static final String CONTACT_POINT = "contactPoint"; + public static final String PORT = "port"; + public static final String QUERY_LOGGER_THRESHOLD = "queryLoggerConstantThreshold"; + public static final String SUNBIRD_CASSANDRA_CONSISTENCY_LEVEL = "sunbird_cassandra_consistency_level"; + public static final String INCOMPLETE_COURSES_MAIL_SUBJECT = "Complete the courses you started"; + public static final String COURSE = "course"; + public static final String _URL = "_url"; + public static final String THUMBNAIL = "_thumbnail"; + public static final String _NAME = "_name"; + public static final String _DURATION = "_duration"; + public static final String SEND_NOTIFICATION_PROPERTIES = "send-notification"; + public static final String NOTIFICATION_HOST = "notification.service.host"; + public static final String NOTIFICATION_ENDPOINT = "notification.event.endpoint"; + public static final String SUBJECT = "subject"; + public static final String SCHEDULER_TIME_GAP = "scheduler-time-gap"; + public static final String SCHEDULER_RUN_DAY = "scheduler-run-day"; + public static final String SCHEDULER_RUN_TIME = "scheduler-run-time"; + public static final String IS_DELETED = "isDeleted"; + public static final String EXCLUDE_USER_EMAILS = "exclude_user_emails"; + public static final String INCOMPLETE_COURSES = "incompletecourses"; + public static final String SUBJECT_ = "subject"; + public static final String POSTER_IMAGE = "posterImage"; - //ratings and review - public static final String API_RATINGS_ADD = "api.ratings.add"; - public static final String API_RATINGS_READ = "api.ratings.read"; - public static final String API_RATINGS_UPDATE = "api.ratings.update"; - public static final String API_RATINGS_SUMMARY = "api.ratings.summary"; - public static final String API_RATINGS_LOOKUP = "api.ratings.lookup"; - public static final String DATABASE = "sunbird"; - public static final String LOGIN_TABLE = "user_first_login_details"; - public static final String ACTIVITY_ID = "activityId"; - public static final String ACTIVITY_TYPE = "activityType"; - public static final String RATINGS_USER_ID = "userId"; - public static final String USER_FIRST_NAME = "firstName"; - public static final String USER_LAST_NAME = "lastName"; - public static final String USERID = "id"; - public static final String COMMENT = "comment"; - public static final String COMMENT_BY = "commentBy"; - public static final String COMMENT_UPDATED_ON = "commentupdatedon"; - public static final String CREATED_ON = "createdon"; - public static final String RATING = "rating"; - public static final String REVIEW = "review"; - public static final String UPDATED_ON = "updatedon"; - public static final String LATEST50REVIEWS = "latest50reviews"; - public static final String SUMMARY_ACTIVITY_ID = "activityid"; - public static final String SUMMARY_ACTIVITY_TYPE = "activitytype"; - public static final String TOTALCOUNT1STARS = "totalcount1stars"; - public static final String TOTALCOUNT2STARS = "totalcount2stars"; - public static final String TOTALCOUNT3STARS = "totalcount3stars"; - public static final String TOTALCOUNT4STARS = "totalcount4stars"; - public static final String TOTALCOUNT5STARS = "totalcount5stars"; - public static final String TOTALNUMBEROFRATINGS = "total_number_of_ratings"; - public static final String SUMOFTOTALRATINGS = "sum_of_total_ratings"; - public static final String NO_RATING_EXCEPTION_MESSAGE = "No ratings found for : "; - public static final String NO_REVIEW_EXCEPTION_MESSAGE = "No reviews found for : "; - public static final String RATING_GENERIC_EXCEPTION_MESSAGE = "Exception occurred while adding the course review : "; - public static final String KAFKA_RATING_EXCEPTION_MESSAGE = "Exception occurred while connecting to kafka topic : "; - public static final String RATING_UPSERT_OPERATION = "upsert"; - public static final String RATING_LOOKUP_RATING_OPERATION = "lookup"; - public static final String RATING_GET_OPERATION = "getRating"; - public static final String RATING_SUMMARY_OPERATION = "getSummary"; - // assessment - public static final String QUESTION_SET = "questionSet"; - public static final String ASSESSMENT_QNS_ANS_SET = "assessmentQnsAnsSet_"; - public static final String ASSESSMENT_QNS_SET = "assessmentQnsSet_"; - // Cassandra Constants - public static final String INSERT_INTO = "INSERT INTO "; - public static final String DOT = "."; - public static final String OPEN_BRACE = "("; - public static final String VALUES_WITH_BRACE = ") VALUES ("; - public static final String QUE_MARK = "?"; - public static final String COMMA = ","; - public static final String CLOSING_BRACE = ");"; - public static final String SUCCESS = "success"; - public static final String UNKNOWN_IDENTIFIER = "Unknown identifier "; - public static final String UNDEFINED_IDENTIFIER = "Undefined column name "; - public static final String EXCEPTION_MSG_FETCH = "Exception occurred while fetching record from "; - public static final String EXCEPTION_MSG_DELETE = "Exception occurred while deleting record from "; - public static final String AUDIT_TYPE = "auditType"; - public static final String CREATED_DATE = "createdDate"; - public static final String CREATED_BY = "createdBy"; - public static final String UPDATED_DATE = "updatedDate"; - public static final String UPDATED_BY = "updatedBy"; - public static final String TRANSACTION_DETAILS = "transactionDetails"; - public static final String PROOF_DOCS = "proofDocs"; - public static final String WORK_ORDER_ID = "workOrderId"; - public static final String WORK_ALLOCATION_ID = "workAllocationId"; - public static final String BEGIN_BATCH = "BEGIN BATCH "; - public static final String APPLY_BATCH = " APPLY BATCH;"; - // Database and Tables - public static final String KEYSPACE_SUNBIRD = "sunbird"; - public static final String KEYSPACE_SUNBIRD_COURSES = "sunbird_courses"; - public static final String TABLE_ORG_BUDGET_SCHEME = "org_budget_scheme"; - public static final String TABLE_USER_ASSESSMENT_TIME= "user_assessment_time"; - public static final String SHA_256_WITH_RSA = "SHA256withRSA"; - public static final String SUB = "sub"; - public static final String _UNAUTHORIZED = "Unauthorized"; - public static final String DOT_SEPARATOR = "."; - public static final String ACCESS_TOKEN_PUBLICKEY_BASEPATH = "accesstoken.publickey.basepath"; - public static final String TABLE_ORG_AUDIT = "org_audit"; - public static final String TABLE_ORG_STAFF_POSITION = "org_staff_position"; - public static final String TABLE_WORK_ORDER = "work_order"; - public static final String TABLE_WORK_ALLOCATION = "work_allocation"; - public static final String TABLE_USER_WORK_ALLOCATION_MAPPING = "user_work_allocation_mapping"; - public static final String TABLE_MANDATORY_USER_CONTENT = "mandatory_user_content"; - public static final String TABLE_ORGANIZATION = "organisation"; - public static final String TABLE_USER_ENROLMENT = "user_enrolments"; - public static final String TABLE_USER = "user"; - public static final String TABLE_COURSE_BATCH = "course_batch"; - public static final String TABLE_RATINGS = "ratings"; - public static final String TABLE_RATINGS_LOOKUP = "ratings_lookup"; - public static final String TABLE_RATINGS_SUMMARY = "ratings_summary"; - public static final String VALUE = "value"; - public static final String DEPT_NAME = "deptName"; - public static final String PROFILE_DETAILS = "profileDetails"; - public static final String CONTENT_TYPE = "Content-Type"; - public static final String APPLICATION_JSON = "application/json"; - public static final String OSID = "osid"; - public static final String INITIATE = "INITIATE"; - public static final String FIELD_KEY = "fieldKey"; - public static final String TO_VALUE = "toValue"; - public static final String FROM_VALUE = "fromValue"; - public static final String STATE = "state"; - public static final String ACTION = "action"; - public static final String APPLICATION_ID = "applicationId"; - public static final String ACTOR_USER_ID = "actorUserId"; - public static final String SERVICE_NAME = "serviceName"; - public static final String PROFILE = "profile"; - public static final String WFID = "wfId"; - public static final String UPDATE_FIELD_VALUES = "updateFieldValues"; - public static final String PROFILE_UPDATE_FIELDS = "profileUpdateFields_"; - public static final String IGOT = "igot"; - public static final String DOPT = "dopt"; - public static final String PERSONAL_DETAILS = "personalDetails"; - public static final String TRANSITION_DETAILS = "transitionDetails"; - public static final String UNAUTHORIZED = "unauthorized"; - // Redis - public static final String API_REDIS_DELETE = "api.redis.delete"; - public static final String API_REDIS_GET_KEYS = "api.redis.get.keys"; - public static final String API_REDIS_GET_KEYS_VALUE_SET = "api.redis.get.keys&values"; - public static final String REDIS_COMMON_KEY = "CB_EXT_"; - public static final String COMPETENCY_CACHE_NAME = "competency"; - public static final String COMPETENCY_CACHE_NAME_BY_AREA = "competencyByArea"; - public static final String COMPETENCY_CACHE_NAME_BY_TYPE = "competencyByType"; - public static final String PROVIDER_CACHE_NAME = "provider"; - public static final String COMPETENCY_FACET_NAME = "competencies_v3.name"; - public static final String IS_TENANT = "isTenant"; - public static final String CHANNEL = "channel"; - public static final String USER_TOKEN = "x-authenticated-user-token"; - public static final String AUTHORIZATION = "authorization"; - public static final String FACETS = "facets"; - public static final String PRIMARY_CATEGORY = "primaryCategory"; - public static final String LIMIT = "limit"; - public static final String REQUEST = "request"; - public static final String FIELDS = "fields"; - public static final String OFFSET = "offset"; - public static final String BUDGET_DOC_UPLOADED_BY = "uploadedBy"; - public static final String BUDGET_DOC_UPLOADED_DATE = "uploadedDate"; - public static final String BUDGET_DOC_FILE_NAME = "fileName"; - public static final String BUDGET_DOC_FILE_TYPE = "fileType"; - public static final String BUDGET_DOC_FILE_SIZE = "fileSize"; - public static final String BUDGET_DOC_FILE_URL = "fileUrl"; - //telemetry audit constants - public static final String ORG_LIST = "ORGANISATION_LIST"; - public static final String VERSION = "3.0.2"; - public static final String EID = "AUDIT"; - public static final String PDATA_ID = "dev.sunbird.cb.ext.service"; - public static final String PDATA_PID = "sunbird-cb-ext-service"; - public static final String TYPE = "WorkOrder"; - public static final String CURRENT_STATE = "FirstLogin"; - public static final String LOGIN_TIME = "login_time"; - public static final List PROPS = Collections.unmodifiableList(Arrays.asList("WAT")); - public static final String USER_CONST = "User"; - public static final String ASSESSMENT_LEVEL_SCORE_CUTOFF = "assessmentlevel"; - public static final String SECTION_LEVEL_SCORE_CUTOFF = "sectionlevel"; - public static final String IDENTIFIER_REPLACER = "{identifier}"; - public static final String CHILDREN = "children"; - public static final String PARAMS = "params"; - public static final String MAX_QUESTIONS = "maxQuestions"; - public static final String CHILD_NODES = "childNodes"; - public static final String SEARCH = "search"; - public static final String QUESTION_ID = "qs_id_"; - public static final String ASSESSMENT_ID = "assess_id_"; - public static final String EDITOR_STATE = "editorState"; - public static final String CHOICES = "choices"; - public static final String ANSWER = "answer"; - public static final String QUESTION = "question"; - public static final String OPTIONS = "options"; - public static final String USER_ASSESS_REQ = "user_assess_req_"; - public static final String HIERARCHY = "hierarchy"; - public static final String DEV_HIERARCHY_STORE = "dev_hierarchy_store"; - public static final String CONTENT_HIERARCHY = "content_hierarchy"; - public static final String BATCH_ID_ = "batchid"; - public static final String COURSE_ID_ = "courseid"; - public static final String COMPLETION_PERCENTAGE_ = "completionpercentage"; - public static final String LAST_ACCESS_TIME = "last_access_time"; - public static final String SUNBIRD_KEY_SPACE_NAME = "sunbird"; - public static final String SUNBIRD_COURSES_KEY_SPACE_NAME = "sunbird_courses"; - public static final String LAST_ACCESS_TIME_GAP = "last.access.time.gap.millis"; - public static final String USER_CONTENT_CONSUMPTION = "user_content_consumption"; - public static final String NOTIFICATION_UTIL = "notificationUtil"; - public static final String NOTIFICATIONS = "notifications"; - public static final String CORE_CONNECTIONS_PER_HOST_FOR_LOCAL = "coreConnectionsPerHostForLocal"; - public static final String CORE_CONNECTIONS_PER_HOST_FOR_REMOTE = - "coreConnectionsPerHostForRemote"; - public static final String MAX_CONNECTIONS_PER_HOST_FOR_LOCAl = "maxConnectionsPerHostForLocal"; - public static final String MAX_CONNECTIONS_PER_HOST_FOR_REMOTE = "maxConnectionsPerHostForRemote"; - public static final String MAX_REQUEST_PER_CONNECTION = "maxRequestsPerConnection"; - public static final String HEARTBEAT_INTERVAL = "heartbeatIntervalSeconds"; - public static final String POOL_TIMEOUT = "poolTimeoutMillis"; - public static final String CONTACT_POINT = "contactPoint"; - public static final String PORT = "port"; - public static final String QUERY_LOGGER_THRESHOLD = "queryLoggerConstantThreshold"; - public static final String SUNBIRD_CASSANDRA_CONSISTENCY_LEVEL = - "sunbird_cassandra_consistency_level"; - public static final String INCOMPLETE_COURSES_MAIL_SUBJECT = "Complete the courses you started"; - public static final String COURSE = "course"; - public static final String _URL = "_url"; - public static final String THUMBNAIL = "_thumbnail"; - public static final String _NAME = "_name"; - public static final String _DURATION = "_duration"; - public static final String SEND_NOTIFICATION_PROPERTIES = "send-notification"; - public static final String NOTIFICATION_HOST = "notification.service.host"; - public static final String NOTIFICATION_ENDPOINT = "notification.event.endpoint"; - public static final String SUBJECT = "subject"; - public static final String SCHEDULER_TIME_GAP = "scheduler-time-gap"; - public static final String SCHEDULER_RUN_DAY = "scheduler-run-day"; - public static final String SCHEDULER_RUN_TIME = "scheduler-run-time"; - public static final String IS_DELETED = "isDeleted"; - public static final String EXCLUDE_USER_EMAILS = "exclude_user_emails"; - public static final String INCOMPLETE_COURSES = "incompletecourses"; - public static final String SUBJECT_ = "subject"; - public static final String POSTER_IMAGE = "posterImage"; + public static final String COURSE_URL = "course.url"; + public static final String OVERVIEW_BATCH_ID = "overview.batch"; + public static final String SENDER_MAIL = "sender.mail"; + public static final String CASSANDRA_CONFIG_HOST = "cassandra.config.host"; + public static final String OBJECT_TYPE = "objectType"; + public static final String QUESTIONS = "questions"; + public static final String RHS_CHOICES = "rhsChoices"; + public static final String MTF_QUESTION = "MTF Question"; + public static final String FTB_QUESTION = "FTB Question"; + public static final String API_QUESTIONSET_HIERARCHY_GET = "api.questionset.hierarchy.get"; + public static final String VER = "3.0"; + public static final String API_QUESTIONS_LIST = "api.questions.list"; + public static final String MINIMUM_PASS_PERCENTAGE = "minimumPassPercentage"; + public static final String SCORE_CUTOFF_TYPE = "scoreCutoffType"; + public static final String PASS_PERCENTAGE = "passPercentage"; + public static final String TOTAL = "total"; + public static final String BLANK = "blank"; + public static final String CORRECT = "correct"; + public static final String INCORRECT = "incorrect"; + public static final String PASS = "pass"; + public static final String OVERALL_RESULT = "overallResult"; + public static final String DO = "do_"; + public static final String SSO_CLIENT_ID = "sso.client.id"; + public static final String SSO_CLIENT_SECRET = "sso.client.secret"; + public static final String SSO_PASSWORD = "sso.password"; + public static final String SSO_POOL_SIZE = "sso.connection.pool.size"; + public static final String SSO_PUBLIC_KEY = "sunbird_sso_publickey"; + public static final String SSO_REALM = "sso.realm"; + public static final String SSO_URL = "sso.url"; + public static final String SSO_USERNAME = "sso.username"; + public static final String SUNBIRD_SSO_CLIENT_ID = "sunbird_sso_client_id"; + public static final String SUNBIRD_SSO_CLIENT_SECRET = "sunbird_sso_client_secret"; + public static final String SUNBIRD_SSO_PASSWORD = "sunbird_sso_password"; + public static final String SUNBIRD_SSO_RELAM = "sunbird_sso_realm"; + public static final String SUNBIRD_SSO_URL = "sunbird_sso_url"; + public static final String SUNBIRD_SSO_USERNAME = "sunbird_sso_username"; + public static final String DURATION = "duration"; + public static final String USER_REGISTRATION_REGISTER_API = "api.user.registration.register"; + public static final String USER_REGISTRATION_UPDATE_API = "api.user.registration.update"; + public static final String USER_REGISTRATION_RETRIEVE_API = "api.user.registration.retrieve"; + public static final String USER_REGISTRATION_DEPT_INFO_API = "api.user.registration.dept.info"; - public static final String COURSE_URL = "course.url"; - public static final String OVERVIEW_BATCH_ID = "overview.batch"; - public static final String SENDER_MAIL = "sender.mail"; - public static final String CASSANDRA_CONFIG_HOST = "cassandra.config.host"; - public static final String OBJECT_TYPE = "objectType"; - public static final String QUESTIONS = "questions"; - public static final String RHS_CHOICES = "rhsChoices"; - public static final String MTF_QUESTION = "MTF Question"; - public static final String FTB_QUESTION = "FTB Question"; - public static final String API_QUESTIONSET_HIERARCHY_GET = "api.questionset.hierarchy.get"; - public static final String VER = "3.0"; - public static final String API_QUESTIONS_LIST = "api.questions.list"; - public static final String MINIMUM_PASS_PERCENTAGE = "minimumPassPercentage"; - public static final String SCORE_CUTOFF_TYPE = "scoreCutoffType"; - public static final String PASS_PERCENTAGE = "passPercentage"; - public static final String TOTAL = "total"; - public static final String BLANK = "blank"; - public static final String CORRECT = "correct"; - public static final String INCORRECT = "incorrect"; - public static final String PASS = "pass"; - public static final String OVERALL_RESULT = "overallResult"; - public static final String DO = "do_"; - public static final String SSO_CLIENT_ID = "sso.client.id"; - public static final String SSO_CLIENT_SECRET = "sso.client.secret"; - public static final String SSO_PASSWORD = "sso.password"; - public static final String SSO_POOL_SIZE = "sso.connection.pool.size"; - public static final String SSO_PUBLIC_KEY = "sunbird_sso_publickey"; - public static final String SSO_REALM = "sso.realm"; - public static final String SSO_URL = "sso.url"; - public static final String SSO_USERNAME = "sso.username"; - public static final String SUNBIRD_SSO_CLIENT_ID = "sunbird_sso_client_id"; - public static final String SUNBIRD_SSO_CLIENT_SECRET = "sunbird_sso_client_secret"; - public static final String SUNBIRD_SSO_PASSWORD = "sunbird_sso_password"; - public static final String SUNBIRD_SSO_RELAM = "sunbird_sso_realm"; - public static final String SUNBIRD_SSO_URL = "sunbird_sso_url"; - public static final String SUNBIRD_SSO_USERNAME = "sunbird_sso_username"; - public static final String DURATION = "duration"; + public static final String API_VERSION_1 = "1.0"; - private Constants() { - throw new IllegalStateException("Utility class"); - } + private Constants() { + throw new IllegalStateException("Utility class"); + } } diff --git a/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java b/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java new file mode 100644 index 000000000..8b1410274 --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java @@ -0,0 +1,36 @@ +package org.sunbird.user.registration.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; +import org.sunbird.common.model.SBApiResponse; +import org.sunbird.user.registration.model.UserRegistrationInfo; +import org.sunbird.user.registration.service.UserRegistrationService; + +/** + * Provides REST APIs creating and updating the User Registration + * + * @author karthik + * + */ +@RestController +public class UserRegistrationController { + + @Autowired + UserRegistrationService userRegService; + + @PostMapping("/user/registration/v1/register") + public ResponseEntity registerUser(@RequestBody UserRegistrationInfo userRegIno) throws Exception { + SBApiResponse response = userRegService.registerUser(userRegIno); + return new ResponseEntity<>(response, response.getResponseCode()); + } + + @GetMapping("/user/registration/v1/getDeptDetails") + public ResponseEntity getDeptDetails() throws Exception { + SBApiResponse response = userRegService.getDeptDetails(); + return new ResponseEntity<>(response, response.getResponseCode()); + } +} diff --git a/src/main/java/org/sunbird/user/registration/model/UserRegistration.java b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java new file mode 100644 index 000000000..0fe6f3a6d --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java @@ -0,0 +1,73 @@ +package org.sunbird.user.registration.model; + +/** + * Model to store user registration details in ES server + * + * @author karthik + * + */ +public class UserRegistration extends UserRegistrationInfo { + private String registrationCode; + private String priviousStatus; + private String status; + private String createdOn; + private String updatedOn; + private String createdBy; + private String updatedBy; + + public String getRegistrationCode() { + return registrationCode; + } + + public void setRegistrationCode(String registrationCode) { + this.registrationCode = registrationCode; + } + + public String getPriviousStatus() { + return priviousStatus; + } + + public void setPriviousStatus(String priviousStatus) { + this.priviousStatus = priviousStatus; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(String createdOn) { + this.createdOn = createdOn; + } + + public String getUpdatedOn() { + return updatedOn; + } + + public void setUpdatedOn(String updatedOn) { + this.updatedOn = updatedOn; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public String getUpdatedBy() { + return updatedBy; + } + + public void setUpdatedBy(String updatedBy) { + this.updatedBy = updatedBy; + } +} diff --git a/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java b/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java new file mode 100644 index 000000000..b6dc90764 --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java @@ -0,0 +1,73 @@ +package org.sunbird.user.registration.model; + +/** + * Model object to store user registration details. + * + * @author karthik + * + */ +public class UserRegistrationInfo { + private String firstName; + private String lastName; + private String email; + private String deptId; + private String deptName; + private String position; + private String source; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getDeptId() { + return deptId; + } + + public void setDeptId(String deptId) { + this.deptId = deptId; + } + + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } + + public String getPosition() { + return position; + } + + public void setPosition(String position) { + this.position = position; + } + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } +} diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java new file mode 100644 index 000000000..97df7d9a6 --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -0,0 +1,31 @@ +package org.sunbird.user.registration.service; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.annotation.TopicPartition; +import org.springframework.stereotype.Component; + +@Component +public class UserRegistrationConsumer { + + @KafkaListener(id = "id1", groupId = "userRegistrationTopic-consumer", topicPartitions = { + @TopicPartition(topic = "${kafka.topics.user.registration.register.event}", partitions = { "0", "1", "2", + "3" }) }) + public void processMessage(ConsumerRecord data) { + /* + * 1. This event should create workflow transition request for user registration + * flow + * + * 2. Upon successful workflow transition request this event should generate an + * email to user. Email should mention User Registration is accepted and + * regisrationCode should be mentioned for subsequent communication + * + * 3. Failure of creating transition request -- should trigger email + * notification to user mentioning the registration request failed and try again + * later. And also update in the ES doc status value. + * + * 4. TODO - In case of transition request created but failed to send email + * notification. + */ + } +} diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java new file mode 100644 index 000000000..63d98281e --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java @@ -0,0 +1,42 @@ +package org.sunbird.user.registration.service; + +import org.springframework.stereotype.Service; +import org.sunbird.common.model.SBApiResponse; +import org.sunbird.user.registration.model.UserRegistrationInfo; + +/** + * Service class which provides CURD operation for User Registration. + * + * @author karthik + * + */ +@Service +public interface UserRegistrationService { + /** + * Registers the given user and creates WorkFlow Service request for approval. + * + * @param userRegInfo - User Registration Information + * @return - Returns the API Response object which contains success / failure + * message + */ + public SBApiResponse registerUser(UserRegistrationInfo userRegInfo); + + /** + * Retrieves the User Registration Code details if exists for the given + * Registration Code value. + * + * @param registrationCode - Registration Code which used to identify the object + * @return - Returns the API Response object which contains success / failure + * message + */ + public SBApiResponse getUserRegistrationDetails(String registrationCode); + + /** + * Retrieves the department details which can be provided user to select upon + * while creating Register request + * + * @return - Returns the API response object which contains success / failure + * message + */ + public SBApiResponse getDeptDetails(); +} diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java new file mode 100644 index 000000000..6a28c8832 --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -0,0 +1,45 @@ +package org.sunbird.user.registration.service; + +import org.joda.time.DateTime; +import org.springframework.http.HttpStatus; +import org.sunbird.common.model.SBApiResponse; +import org.sunbird.common.model.SunbirdApiRespParam; +import org.sunbird.common.util.Constants; +import org.sunbird.user.registration.model.UserRegistrationInfo; + +public class UserRegistrationServiceImpl implements UserRegistrationService { + + public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { + // This method should perform the following + // 1. verify the incoming data is proper + // 2. verify the incoming email is valid domain + // 3. verify the given email is exist in ES Server + // 4. create the doc in ES and fire Kafka topic event + // 5. return 200 OK response once the ES entry created successfully. + + SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_REGISTER_API); + response.setResponseCode(HttpStatus.ACCEPTED); + return response; + } + + public SBApiResponse getUserRegistrationDetails(String registrationCode) { + SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_RETRIEVE_API); + return response; + } + + public SBApiResponse getDeptDetails() { + SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_DEPT_INFO_API); + return response; + } + + private SBApiResponse createDefaultResponse(String api) { + SBApiResponse response = new SBApiResponse(); + response.setId(api); + response.setVer(Constants.API_VERSION_1); + response.setParams(new SunbirdApiRespParam()); + response.getParams().setStatus(Constants.SUCCESS); + response.setResponseCode(HttpStatus.OK); + response.setTs(DateTime.now().toString()); + return response; + } +} diff --git a/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java b/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java new file mode 100644 index 000000000..339a99ffd --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java @@ -0,0 +1,22 @@ +package org.sunbird.user.registration.util; + +/** + * This Enum provides various status values for User Registration flow. + * + * @author karthik + * + */ +public enum UserRegistrationStatus { + + INITIATED(0), CREATED(1), APPROVED(2), DENIED(3), FAILED(4); + + private int status = 0; + + UserRegistrationStatus(int status) { + this.status = status; + } + + public int getStatus() { + return status; + } +} From 22f8f28a622e5ec7bf1568fac13c9d29719855bb Mon Sep 17 00:00:00 2001 From: nivetha Date: Sun, 29 May 2022 22:52:01 +0530 Subject: [PATCH 02/22] user registration impl --- .../common/util/CbExtServerProperties.java | 34 +++++ .../registration/model/UserRegistration.java | 23 ++- .../user/registration/model/WfRequest.java | 108 +++++++++++++ .../service/UserRegistrationConsumer.java | 78 +++++++++- .../service/UserRegistrationService.java | 8 +- .../service/UserRegistrationServiceImpl.java | 142 +++++++++++++++++- .../user/registration/util/Utility.java | 23 +++ .../service/IndexerService.java | 24 ++- src/main/resources/application.properties | 4 + 9 files changed, 418 insertions(+), 26 deletions(-) create mode 100644 src/main/java/org/sunbird/user/registration/model/WfRequest.java create mode 100644 src/main/java/org/sunbird/user/registration/util/Utility.java diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index e36b370c6..d90f18c31 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -228,6 +228,15 @@ public class CbExtServerProperties { @Value("${user.assessment.submission.duration}") private String userAssessmentSubmissionDuration; + @Value("${es.user.registration.index}") + private String userRegistrationIndex; + + @Value("${user.registration.code}") + private String userRegistrationCode; + + @Value("${kafka.topics.user.registration.register.event}") + private String userRegistrationTopic; + public String getUserAssessmentSubmissionDuration() { return userAssessmentSubmissionDuration; } @@ -830,4 +839,29 @@ public List getAssessmentMinQuestionParams() { public void setAssessmentMinQuestionParams(String assessmentMinQuestionParams) { this.assessmentMinQuestionParams = assessmentMinQuestionParams; } + + public String getUserRegistrationIndex() { + return userRegistrationIndex; + } + + public void setUserRegistrationIndex(String userRegistrationIndex) { + this.userRegistrationIndex = userRegistrationIndex; + } + + public String getUserRegistrationCode() { + return userRegistrationCode; + } + + public void setUserRegistrationCode(String userRegistrationCode) { + this.userRegistrationCode = userRegistrationCode; + } + + public String getUserRegistrationTopic() { + return userRegistrationTopic; + } + + public void setUserRegistrationTopic(String userRegistrationTopic) { + this.userRegistrationTopic = userRegistrationTopic; + } + } \ No newline at end of file diff --git a/src/main/java/org/sunbird/user/registration/model/UserRegistration.java b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java index 0fe6f3a6d..1783389e3 100644 --- a/src/main/java/org/sunbird/user/registration/model/UserRegistration.java +++ b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java @@ -7,14 +7,23 @@ * */ public class UserRegistration extends UserRegistrationInfo { + private String id; private String registrationCode; private String priviousStatus; private String status; - private String createdOn; - private String updatedOn; + private long createdOn; + private long updatedOn; private String createdBy; private String updatedBy; + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + public String getRegistrationCode() { return registrationCode; } @@ -22,7 +31,7 @@ public String getRegistrationCode() { public void setRegistrationCode(String registrationCode) { this.registrationCode = registrationCode; } - + public String getPriviousStatus() { return priviousStatus; } @@ -39,19 +48,19 @@ public void setStatus(String status) { this.status = status; } - public String getCreatedOn() { + public long getCreatedOn() { return createdOn; } - public void setCreatedOn(String createdOn) { + public void setCreatedOn(long createdOn) { this.createdOn = createdOn; } - public String getUpdatedOn() { + public long getUpdatedOn() { return updatedOn; } - public void setUpdatedOn(String updatedOn) { + public void setUpdatedOn(long updatedOn) { this.updatedOn = updatedOn; } diff --git a/src/main/java/org/sunbird/user/registration/model/WfRequest.java b/src/main/java/org/sunbird/user/registration/model/WfRequest.java new file mode 100644 index 000000000..913391b88 --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/model/WfRequest.java @@ -0,0 +1,108 @@ +package org.sunbird.user.registration.model; + +import java.util.HashMap; +import java.util.List; + +public class WfRequest { + + private String state; + + private String action; + + private String applicationId; + + private String userId; + + private String actorUserId; + + private String wfId; + + private List> updateFieldValues; + + private String comment; + + private String serviceName; + + private String deptName; + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(String applicationId) { + this.applicationId = applicationId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getActorUserId() { + return actorUserId; + } + + public void setActorUserId(String actorUserId) { + this.actorUserId = actorUserId; + } + + public String getWfId() { + return wfId; + } + + public void setWfId(String wfId) { + this.wfId = wfId; + } + + public List> getUpdateFieldValues() { + return updateFieldValues; + } + + public void setUpdateFieldValues(List> updateFieldValues) { + this.updateFieldValues = updateFieldValues; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getDeptName() { + return deptName; + } + + public void setDeptName(String deptName) { + this.deptName = deptName; + } + +} diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index 97df7d9a6..554cb215d 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -1,25 +1,60 @@ package org.sunbird.user.registration.service; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.annotation.TopicPartition; import org.springframework.stereotype.Component; +import org.sunbird.common.service.OutboundRequestHandlerServiceImpl; +import org.sunbird.common.util.CbExtServerProperties; +import org.sunbird.common.util.Constants; +import org.sunbird.common.util.NotificationUtil; +import org.sunbird.common.util.PropertiesCache; +import org.sunbird.user.registration.model.UserRegistration; +import org.sunbird.user.registration.model.WfRequest; + +import com.google.gson.Gson; @Component public class UserRegistrationConsumer { + private static final Logger LOGGER = LoggerFactory.getLogger(UserRegistrationConsumer.class); + + Gson gson = new Gson(); + + @Autowired + OutboundRequestHandlerServiceImpl outboundHandlerService; + + @Autowired + CbExtServerProperties serverProperties; + + @Autowired + NotificationUtil notificationUtil; + @KafkaListener(id = "id1", groupId = "userRegistrationTopic-consumer", topicPartitions = { @TopicPartition(topic = "${kafka.topics.user.registration.register.event}", partitions = { "0", "1", "2", "3" }) }) public void processMessage(ConsumerRecord data) { + UserRegistration userRegistration = gson.fromJson(data.value(), UserRegistration.class); /* * 1. This event should create workflow transition request for user registration * flow - * + */ + WfRequest wfRequest = wfRequestObj(userRegistration); + Boolean wfTransition = workflowTransition(wfRequest); + + /* * 2. Upon successful workflow transition request this event should generate an * email to user. Email should mention User Registration is accepted and * regisrationCode should be mentioned for subsequent communication - * + * * 3. Failure of creating transition request -- should trigger email * notification to user mentioning the registration request failed and try again * later. And also update in the ES doc status value. @@ -27,5 +62,44 @@ public void processMessage(ConsumerRecord data) { * 4. TODO - In case of transition request created but failed to send email * notification. */ + if (wfTransition) { + List sendTo = new ArrayList() { + { + add(userRegistration.getEmail()); + } + }; + Map params = null; + notificationUtil.sendNotification(sendTo, params, + PropertiesCache.getInstance().getProperty(Constants.SENDER_MAIL), + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) + + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT)); + } + + } + + private WfRequest wfRequestObj(UserRegistration userRegistration) { + WfRequest wfRequest = new WfRequest(); + return wfRequest; + } + + private Boolean workflowTransition(WfRequest wfRequest) { + try { + HashMap headerValues = new HashMap<>(); + headerValues.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); + headerValues.put(Constants.ROOT_ORG_CONSTANT, Constants.IGOT); + headerValues.put(Constants.ORG_CONSTANT, Constants.DOPT); + + Map responseObject = outboundHandlerService.fetchResultUsingPost( + serverProperties.getWfServiceHost() + serverProperties.getWfServiceTransitionPath(), wfRequest, + headerValues); + Map resultValue = (Map) responseObject.get(Constants.RESULT); + if (resultValue.get(Constants.STATUS).equals(Constants.OK)) { + return Boolean.TRUE; + } + + } catch (Exception e) { + LOGGER.error(String.format("Exception in %s : %s", "workflowTransition", e.getMessage())); + } + return Boolean.FALSE; } } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java index 63d98281e..48cf0f614 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java @@ -1,6 +1,5 @@ package org.sunbird.user.registration.service; -import org.springframework.stereotype.Service; import org.sunbird.common.model.SBApiResponse; import org.sunbird.user.registration.model.UserRegistrationInfo; @@ -10,12 +9,12 @@ * @author karthik * */ -@Service public interface UserRegistrationService { /** * Registers the given user and creates WorkFlow Service request for approval. * - * @param userRegInfo - User Registration Information + * @param userRegInfo + * - User Registration Information * @return - Returns the API Response object which contains success / failure * message */ @@ -25,7 +24,8 @@ public interface UserRegistrationService { * Retrieves the User Registration Code details if exists for the given * Registration Code value. * - * @param registrationCode - Registration Code which used to identify the object + * @param registrationCode + * - Registration Code which used to identify the object * @return - Returns the API Response object which contains success / failure * message */ diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index 6a28c8832..6aebb004a 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -1,24 +1,88 @@ package org.sunbird.user.registration.service; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang.StringUtils; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.search.builder.SearchSourceBuilder; import org.joda.time.DateTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; import org.sunbird.common.model.SBApiResponse; import org.sunbird.common.model.SunbirdApiRespParam; +import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; +import org.sunbird.core.producer.Producer; +import org.sunbird.user.registration.model.UserRegistration; import org.sunbird.user.registration.model.UserRegistrationInfo; +import org.sunbird.user.registration.util.UserRegistrationStatus; +import org.sunbird.user.registration.util.Utility; +import org.sunbird.workallocation.service.IndexerService; + +import com.fasterxml.jackson.databind.ObjectMapper; +@Service public class UserRegistrationServiceImpl implements UserRegistrationService { + private Logger LOGGER = LoggerFactory.getLogger(UserRegistrationServiceImpl.class); + + ObjectMapper mapper = new ObjectMapper(); + + @Autowired + CbExtServerProperties serverProperties; + + @Autowired + IndexerService indexerService; + + @Autowired + Producer kafkaProducer; + public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { - // This method should perform the following - // 1. verify the incoming data is proper - // 2. verify the incoming email is valid domain - // 3. verify the given email is exist in ES Server - // 4. create the doc in ES and fire Kafka topic event - // 5. return 200 OK response once the ES entry created successfully. SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_REGISTER_API); - response.setResponseCode(HttpStatus.ACCEPTED); + String payloadvalidation = validateRegisterationPayload(userRegInfo); + if (StringUtils.isBlank(payloadvalidation)) { + try { + // verify the given email is exist in ES Server + SearchSourceBuilder searchSourceBuilder = queryBuilder(new HashMap() { + { + put(Constants.EMAIL, userRegInfo.getEmail()); + } + }); + long emailExist = indexerService.getDocumentCount(serverProperties.getUserRegistrationIndex(), + searchSourceBuilder); + if (emailExist == 0l) { + // create the doc in ES + UserRegistration userRegistration = getRegistrationObject(userRegInfo); + RestStatus status = indexerService.addEntity(serverProperties.getUserRegistrationIndex(), + serverProperties.getEsProfileIndexType(), userRegistration.getId(), + mapper.convertValue(userRegistration, Map.class)); + if (status.equals(RestStatus.CREATED)) { + // fire Kafka topic event + kafkaProducer.push(serverProperties.getUserRegistrationTopic(), userRegistration); + response.setResponseCode(HttpStatus.ACCEPTED); + } + } else { + payloadvalidation = "Email id already exists"; + } + } catch (Exception e) { + LOGGER.error(String.format("Exception in %s : %s", "registerUser", e.getMessage())); + } + } + if (StringUtils.isNotBlank(payloadvalidation)) { + response.getParams().setStatus(Constants.FAILED); + response.getParams().setErrmsg(payloadvalidation); + response.setResponseCode(HttpStatus.BAD_REQUEST); + } + return response; } @@ -42,4 +106,68 @@ private SBApiResponse createDefaultResponse(String api) { response.setTs(DateTime.now().toString()); return response; } + + private String validateRegisterationPayload(UserRegistrationInfo userRegInfo) { + if (StringUtils.isBlank(userRegInfo.getFirstName())) { + return "Firstname missing"; + } + if (StringUtils.isBlank(userRegInfo.getLastName())) { + return "Lastname missing"; + } + if (StringUtils.isBlank(userRegInfo.getEmail())) { + return "Email missing"; + } + if (StringUtils.isBlank(userRegInfo.getDeptId())) { + return "Department Id missing"; + } + if (StringUtils.isBlank(userRegInfo.getDeptName())) { + return "Department name missing"; + } + if (StringUtils.isBlank(userRegInfo.getPosition())) { + return "Position missing"; + } + if (StringUtils.isBlank(userRegInfo.getSource())) { + return "Source missing"; + } + // email Validation + if (!Utility.emailValidation(userRegInfo.getEmail())) { + return "Invalid email id"; + } + + return StringUtils.EMPTY; + } + + private UserRegistration getRegistrationObject(UserRegistrationInfo userRegInfo) { + UserRegistration userRegistration = new UserRegistration(); + userRegistration.setFirstName(userRegInfo.getFirstName()); + userRegistration.setLastName(userRegInfo.getLastName()); + userRegistration.setEmail(userRegInfo.getEmail()); + userRegistration.setDeptId(userRegInfo.getDeptId()); + userRegistration.setDeptName(userRegInfo.getDeptName()); + userRegistration.setPosition(userRegInfo.getPosition()); + userRegistration.setSource(userRegInfo.getSource()); + + userRegistration.setRegistrationCode(serverProperties.getUserRegistrationCode() + "-" + + userRegInfo.getDeptName() + "-" + RandomStringUtils.random(15, Boolean.TRUE, Boolean.TRUE)); + userRegistration.setId(RandomStringUtils.random(15, Boolean.TRUE, Boolean.TRUE)); + userRegistration.setStatus(UserRegistrationStatus.INITIATED.name()); + userRegistration.setCreatedOn(new Date().getTime()); + return userRegistration; + } + + /** + * Elasticsearch must match bool search query builder + * + * @param mustMatch + * Map + * @return SearchSourceBuilder + */ + private SearchSourceBuilder queryBuilder(Map mustMatch) { + BoolQueryBuilder boolBuilder = new BoolQueryBuilder(); + SearchSourceBuilder searchBuilder = new SearchSourceBuilder().query(boolBuilder); + for (Map.Entry entry : mustMatch.entrySet()) { + boolBuilder.must(QueryBuilders.matchQuery(entry.getKey() + ".keyword", entry.getValue())); + } + return searchBuilder; + } } diff --git a/src/main/java/org/sunbird/user/registration/util/Utility.java b/src/main/java/org/sunbird/user/registration/util/Utility.java new file mode 100644 index 000000000..5d727c352 --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/util/Utility.java @@ -0,0 +1,23 @@ +package org.sunbird.user.registration.util; + +import java.util.regex.Pattern; + +public class Utility { + + /** + * Check the email id is valid or not + * + * @param email + * String + * @return Boolean + */ + public static Boolean emailValidation(String email) { + String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\." + "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + + "A-Z]{2,7}$"; + + Pattern pat = Pattern.compile(emailRegex); + return (email == null) ? Boolean.FALSE : pat.matcher(email).matches(); + + } + +} diff --git a/src/main/java/org/sunbird/workallocation/service/IndexerService.java b/src/main/java/org/sunbird/workallocation/service/IndexerService.java index 7eafb080c..26617be22 100644 --- a/src/main/java/org/sunbird/workallocation/service/IndexerService.java +++ b/src/main/java/org/sunbird/workallocation/service/IndexerService.java @@ -1,7 +1,9 @@ package org.sunbird.workallocation.service; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.List; +import java.util.Map; + import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.get.GetRequest; @@ -14,6 +16,8 @@ import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; +import org.elasticsearch.client.core.CountRequest; +import org.elasticsearch.client.core.CountResponse; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.slf4j.Logger; @@ -23,10 +27,6 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; -import java.io.IOException; -import java.util.List; -import java.util.Map; - @Service public class IndexerService { @@ -132,4 +132,16 @@ public RestStatus BulkInsert(List indexRequestList) { return null; return restStatus.status(); } + + public long getDocumentCount(String index, SearchSourceBuilder searchSourceBuilder) { + try { + CountRequest countRequest = new CountRequest().indices(index); + countRequest.source(searchSourceBuilder); + CountResponse countResponse = esClient.count(countRequest, RequestOptions.DEFAULT); + return countResponse.getCount(); + } catch (Exception e) { + logger.error(String.format("Exception in getDocumentCount: %s", e.getMessage())); + return 0l; + } + } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index b85b0316c..c77676e08 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -44,6 +44,7 @@ es.password= es.profile.index=userprofile es.profile.index.type=_doc es.profile.source.fields=photo,id,employmentDetails,personalDetails +es.user.registration.index=user-registration #workallocation es config @@ -61,6 +62,7 @@ kafka.topics.wat.telemetry.event=watTelemetryTopic kafka.topics.parent.telemetry.event=dev.telemetry.raw kafka.topics.parent.rating.event = dev.rating.event kafka.topics.userutility.telemetry.event=userLastLoginTopic +kafka.topics.user.registration.register.event=userRegistration userutility.telemetry.event.pdata.id=dev.sunbird.cb.ext.service userutility.telemetry.event.pdata.pid=sunbird-cb-ext-service @@ -173,3 +175,5 @@ sso.username=admin sunbird_sso_client_secret=e9899c3c-bf7f-4bc8-972b-959a1d2e3d57 accesstoken.publickey.basepath=/home/juhi/keys/U2JTvZDDV8xo7fk_4wuc-d5Rf64OLmhziQEHcGnUshM user.assessment.submission.duration=120 + +user.registration.code=iGOT From d5670f77fd5702ed1bf03e401120b7602eed6a54 Mon Sep 17 00:00:00 2001 From: Karthikeyan Rajendran <70887864+karthik-tarento@users.noreply.github.com> Date: Mon, 30 May 2022 09:28:03 +0530 Subject: [PATCH 03/22] Adding userRegistration mappings file --- .../index/userRegistration_v1.json | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 src/main/resources/elasticsearch/index/userRegistration_v1.json diff --git a/src/main/resources/elasticsearch/index/userRegistration_v1.json b/src/main/resources/elasticsearch/index/userRegistration_v1.json new file mode 100644 index 000000000..2c71d8b0c --- /dev/null +++ b/src/main/resources/elasticsearch/index/userRegistration_v1.json @@ -0,0 +1,145 @@ +{ + "mappings": { + "_doc": { + "properties": { + "id": { + "type": "keyword", + "fields": { + "raw": { + "type": "keyword" + } + } + }, + "registrationCode": { + "type": "keyword", + "fields": { + "raw": { + "type": "keyword" + } + } + }, + "firstName": { + "type": "text", + "fields": { + "raw": { + "type": "text", + "analyzer": "keylower" + } + }, + "analyzer": "cs_index_analyzer", + "search_analyzer": "cs_search_analyzer" + }, + "lastName": { + "type": "text", + "fields": { + "raw": { + "type": "text", + "analyzer": "keylower" + } + }, + "analyzer": "cs_index_analyzer", + "search_analyzer": "cs_search_analyzer" + }, + "email": { + "type": "keyword", + "fields": { + "raw": { + "type": "text", + "analyzer": "keylower" + } + } + }, + "deptName": { + "type": "text", + "fields": { + "raw": { + "type": "text", + "analyzer": "keylower" + } + }, + "analyzer": "cs_search_analyzer", + "search_analyzer": "cs_search_analyzer" + }, + "deptId": { + "type": "keyword", + "fields": { + "raw": { + "type": "keyword" + } + } + }, + "position": { + "type": "text", + "fields": { + "raw": { + "type": "text", + "analyzer": "keylower" + } + }, + "analyzer": "cs_search_analyzer", + "search_analyzer": "cs_search_analyzer" + }, + "source": { + "type": "keyword", + "fields": { + "raw": { + "type": "keyword" + } + } + }, + "status": { + "type": "keyword", + "fields": { + "raw": { + "type": "keyword" + } + } + }, + "priviousStatus": { + "type": "keyword", + "fields": { + "raw": { + "type": "keyword" + } + } + }, + "createdBy": { + "type": "keyword", + "fields": { + "raw": { + "type": "keyword" + } + } + }, + "createdOn": { + "type": "text", + "fields": { + "raw": { + "type": "keyword" + } + }, + "analyzer": "cs_search_analyzer", + "search_analyzer": "cs_search_analyzer" + }, + "updatedBy": { + "type": "keyword", + "fields": { + "raw": { + "type": "keyword" + } + } + }, + "updatedOn": { + "type": "text", + "fields": { + "raw": { + "type": "keyword" + } + }, + "analyzer": "cs_search_analyzer", + "search_analyzer": "cs_search_analyzer" + } + } + } + } +} From bec8cc4c006e353321298a7a6d78c93397ab5696 Mon Sep 17 00:00:00 2001 From: nivetha Date: Mon, 30 May 2022 12:03:23 +0530 Subject: [PATCH 04/22] Review changes --- .../common/util/CbExtServerProperties.java | 23 +++-- .../util}/IndexerService.java | 2 +- .../UserRegistrationController.java | 7 +- .../registration/model/UserRegistration.java | 11 +-- .../model/UserRegistrationInfo.java | 10 +++ .../service/UserRegistrationConsumer.java | 90 +++++++++++++++---- .../service/UserRegistrationService.java | 8 -- .../service/UserRegistrationServiceImpl.java | 79 ++++++++++++---- .../util/UserRegistrationStatus.java | 2 +- .../user/registration/util/Utility.java | 20 ++++- .../service/AllocationService.java | 1 + .../service/AllocationServiceV2.java | 1 + .../workallocation/util/Validator.java | 2 +- src/main/resources/application.properties | 3 +- 14 files changed, 198 insertions(+), 61 deletions(-) rename src/main/java/org/sunbird/{workallocation/service => common/util}/IndexerService.java (99%) diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index d90f18c31..b856185e8 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -231,12 +231,15 @@ public class CbExtServerProperties { @Value("${es.user.registration.index}") private String userRegistrationIndex; - @Value("${user.registration.code}") - private String userRegistrationCode; + @Value("${user.registration.code.prefix}") + private String userRegCodePrefix; @Value("${kafka.topics.user.registration.register.event}") private String userRegistrationTopic; + @Value("${user.registration.domain}") + private String userRegistrationDomain; + public String getUserAssessmentSubmissionDuration() { return userAssessmentSubmissionDuration; } @@ -848,12 +851,12 @@ public void setUserRegistrationIndex(String userRegistrationIndex) { this.userRegistrationIndex = userRegistrationIndex; } - public String getUserRegistrationCode() { - return userRegistrationCode; + public String getUserRegCodePrefix() { + return userRegCodePrefix; } - public void setUserRegistrationCode(String userRegistrationCode) { - this.userRegistrationCode = userRegistrationCode; + public void setUserRegCodePrefix(String userRegCodePrefix) { + this.userRegCodePrefix = userRegCodePrefix; } public String getUserRegistrationTopic() { @@ -864,4 +867,12 @@ public void setUserRegistrationTopic(String userRegistrationTopic) { this.userRegistrationTopic = userRegistrationTopic; } + public String getUserRegistrationDomain() { + return userRegistrationDomain; + } + + public void setUserRegistrationDomain(String userRegistrationDomain) { + this.userRegistrationDomain = userRegistrationDomain; + } + } \ No newline at end of file diff --git a/src/main/java/org/sunbird/workallocation/service/IndexerService.java b/src/main/java/org/sunbird/common/util/IndexerService.java similarity index 99% rename from src/main/java/org/sunbird/workallocation/service/IndexerService.java rename to src/main/java/org/sunbird/common/util/IndexerService.java index 26617be22..7211d4c15 100644 --- a/src/main/java/org/sunbird/workallocation/service/IndexerService.java +++ b/src/main/java/org/sunbird/common/util/IndexerService.java @@ -1,4 +1,4 @@ -package org.sunbird.workallocation.service; +package org.sunbird.common.util; import java.io.IOException; import java.util.List; diff --git a/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java b/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java index 8b1410274..002073ff5 100644 --- a/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java +++ b/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java @@ -5,6 +5,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.sunbird.common.model.SBApiResponse; import org.sunbird.user.registration.model.UserRegistrationInfo; @@ -28,9 +29,9 @@ public ResponseEntity registerUser(@RequestBody UserRegistrationI return new ResponseEntity<>(response, response.getResponseCode()); } - @GetMapping("/user/registration/v1/getDeptDetails") - public ResponseEntity getDeptDetails() throws Exception { - SBApiResponse response = userRegService.getDeptDetails(); + @GetMapping("/user/registration/v1/getUserRegistrationDetails") + public ResponseEntity getUserRegistrationDetails(@RequestParam String regCode) throws Exception { + SBApiResponse response = userRegService.getUserRegistrationDetails(regCode); return new ResponseEntity<>(response, response.getResponseCode()); } } diff --git a/src/main/java/org/sunbird/user/registration/model/UserRegistration.java b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java index 1783389e3..89490ad35 100644 --- a/src/main/java/org/sunbird/user/registration/model/UserRegistration.java +++ b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java @@ -8,7 +8,7 @@ */ public class UserRegistration extends UserRegistrationInfo { private String id; - private String registrationCode; + private String wfId; private String priviousStatus; private String status; private long createdOn; @@ -24,12 +24,12 @@ public void setId(String id) { this.id = id; } - public String getRegistrationCode() { - return registrationCode; + public String getWfId() { + return wfId; } - public void setRegistrationCode(String registrationCode) { - this.registrationCode = registrationCode; + public void setWfId(String wfId) { + this.wfId = wfId; } public String getPriviousStatus() { @@ -79,4 +79,5 @@ public String getUpdatedBy() { public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } + } diff --git a/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java b/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java index b6dc90764..762880dce 100644 --- a/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java +++ b/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java @@ -7,6 +7,7 @@ * */ public class UserRegistrationInfo { + private String registrationCode; private String firstName; private String lastName; private String email; @@ -15,6 +16,14 @@ public class UserRegistrationInfo { private String position; private String source; + public String getRegistrationCode() { + return registrationCode; + } + + public void setRegistrationCode(String registrationCode) { + this.registrationCode = registrationCode; + } + public String getFirstName() { return firstName; } @@ -70,4 +79,5 @@ public String getSource() { public void setSource(String source) { this.source = source; } + } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index 554cb215d..88ec9ab61 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -1,11 +1,13 @@ package org.sunbird.user.registration.service; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.elasticsearch.rest.RestStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -15,11 +17,13 @@ import org.sunbird.common.service.OutboundRequestHandlerServiceImpl; import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; +import org.sunbird.common.util.IndexerService; import org.sunbird.common.util.NotificationUtil; import org.sunbird.common.util.PropertiesCache; import org.sunbird.user.registration.model.UserRegistration; import org.sunbird.user.registration.model.WfRequest; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; @Component @@ -29,6 +33,8 @@ public class UserRegistrationConsumer { Gson gson = new Gson(); + ObjectMapper mapper = new ObjectMapper(); + @Autowired OutboundRequestHandlerServiceImpl outboundHandlerService; @@ -38,6 +44,9 @@ public class UserRegistrationConsumer { @Autowired NotificationUtil notificationUtil; + @Autowired + IndexerService indexerService; + @KafkaListener(id = "id1", groupId = "userRegistrationTopic-consumer", topicPartitions = { @TopicPartition(topic = "${kafka.topics.user.registration.register.event}", partitions = { "0", "1", "2", "3" }) }) @@ -48,8 +57,7 @@ public void processMessage(ConsumerRecord data) { * flow */ WfRequest wfRequest = wfRequestObj(userRegistration); - Boolean wfTransition = workflowTransition(wfRequest); - + Map wfTransitionData = workflowTransition(wfRequest); /* * 2. Upon successful workflow transition request this event should generate an * email to user. Email should mention User Registration is accepted and @@ -62,30 +70,47 @@ public void processMessage(ConsumerRecord data) { * 4. TODO - In case of transition request created but failed to send email * notification. */ - if (wfTransition) { - List sendTo = new ArrayList() { - { - add(userRegistration.getEmail()); - } - }; - Map params = null; - notificationUtil.sendNotification(sendTo, params, - PropertiesCache.getInstance().getProperty(Constants.SENDER_MAIL), - PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) - + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT)); + if (wfTransitionData != null) { + List wfIds = (List) wfTransitionData.get("wfIds"); + userRegistration.setStatus((String) wfTransitionData.get(Constants.STATUS)); + userRegistration.setWfId(wfIds.get(0)); + RestStatus status = indexerService.addEntity(serverProperties.getUserRegistrationIndex(), + serverProperties.getEsProfileIndexType(), userRegistration.getId(), + mapper.convertValue(userRegistration, Map.class)); + + if (status.equals(RestStatus.CREATED)) { + // send notification + List sendTo = new ArrayList() { + { + add(userRegistration.getEmail()); + } + }; + Map params = notificationPayload(); + notificationUtil.sendNotification(sendTo, params, + PropertiesCache.getInstance().getProperty(Constants.SENDER_MAIL), + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) + + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT)); + } + } } private WfRequest wfRequestObj(UserRegistration userRegistration) { WfRequest wfRequest = new WfRequest(); + wfRequest.setState(userRegistration.getStatus()); + wfRequest.setAction(userRegistration.getStatus()); + wfRequest.setUserId("1234"); + wfRequest.setActorUserId("1234"); + wfRequest.setApplicationId(userRegistration.getId()); + wfRequest.setServiceName("user-registration"); + wfRequest.setUpdateFieldValues(Arrays.asList(new HashMap<>())); return wfRequest; } - private Boolean workflowTransition(WfRequest wfRequest) { + private Map workflowTransition(WfRequest wfRequest) { try { - HashMap headerValues = new HashMap<>(); - headerValues.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); + Map headerValues = new HashMap<>(); headerValues.put(Constants.ROOT_ORG_CONSTANT, Constants.IGOT); headerValues.put(Constants.ORG_CONSTANT, Constants.DOPT); @@ -94,12 +119,41 @@ private Boolean workflowTransition(WfRequest wfRequest) { headerValues); Map resultValue = (Map) responseObject.get(Constants.RESULT); if (resultValue.get(Constants.STATUS).equals(Constants.OK)) { - return Boolean.TRUE; + return (Map) resultValue.get("data"); } } catch (Exception e) { LOGGER.error(String.format("Exception in %s : %s", "workflowTransition", e.getMessage())); } - return Boolean.FALSE; + return null; } + + private Map notificationPayload() { + Map notificationObj = new HashMap<>(); + notificationObj.put("mode", "email"); + notificationObj.put("deliveryType", "message"); + notificationObj.put("config", new HashMap() { + { + put("sender", ""); + put("subject", ""); + } + }); + notificationObj.put("ids", new ArrayList() { + { + add(""); + } + }); + notificationObj.put("template", new HashMap() { + { + put("data", ""); + put("params", new HashMap() { + { + put("", ""); + } + }); + } + }); + return notificationObj; + } + } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java index 48cf0f614..abb438fcb 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java @@ -31,12 +31,4 @@ public interface UserRegistrationService { */ public SBApiResponse getUserRegistrationDetails(String registrationCode); - /** - * Retrieves the department details which can be provided user to select upon - * while creating Register request - * - * @return - Returns the API response object which contains success / failure - * message - */ - public SBApiResponse getDeptDetails(); } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index 6aebb004a..929a48b49 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -6,9 +6,11 @@ import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; +import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.joda.time.DateTime; import org.slf4j.Logger; @@ -20,12 +22,12 @@ import org.sunbird.common.model.SunbirdApiRespParam; import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; +import org.sunbird.common.util.IndexerService; import org.sunbird.core.producer.Producer; import org.sunbird.user.registration.model.UserRegistration; import org.sunbird.user.registration.model.UserRegistrationInfo; import org.sunbird.user.registration.util.UserRegistrationStatus; import org.sunbird.user.registration.util.Utility; -import org.sunbird.workallocation.service.IndexerService; import com.fasterxml.jackson.databind.ObjectMapper; @@ -45,23 +47,26 @@ public class UserRegistrationServiceImpl implements UserRegistrationService { @Autowired Producer kafkaProducer; + @Override public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_REGISTER_API); String payloadvalidation = validateRegisterationPayload(userRegInfo); if (StringUtils.isBlank(payloadvalidation)) { try { - // verify the given email is exist in ES Server - SearchSourceBuilder searchSourceBuilder = queryBuilder(new HashMap() { + // verify the given email exist in ES Server + UserRegistration regDocument = getUserRegistrationDocument(new HashMap() { { put(Constants.EMAIL, userRegInfo.getEmail()); } }); - long emailExist = indexerService.getDocumentCount(serverProperties.getUserRegistrationIndex(), - searchSourceBuilder); - if (emailExist == 0l) { + if (regDocument == null || (regDocument.getStatus().equals(UserRegistrationStatus.FAILED.name()) + && regDocument.getRegistrationCode().equals(regDocument.getRegistrationCode()))) { // create the doc in ES UserRegistration userRegistration = getRegistrationObject(userRegInfo); + if (StringUtils.isBlank(userRegistration.getId())) { + userRegistration.setId(regDocument.getId()); + } RestStatus status = indexerService.addEntity(serverProperties.getUserRegistrationIndex(), serverProperties.getEsProfileIndexType(), userRegistration.getId(), mapper.convertValue(userRegistration, Map.class)); @@ -71,8 +76,11 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { response.setResponseCode(HttpStatus.ACCEPTED); } } else { - payloadvalidation = "Email id already exists"; + payloadvalidation = regDocument.getStatus().equals(UserRegistrationStatus.FAILED.name()) + ? "Registration code is missing" + : "Email id already exists"; } + } catch (Exception e) { LOGGER.error(String.format("Exception in %s : %s", "registerUser", e.getMessage())); } @@ -86,13 +94,29 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { return response; } + @Override public SBApiResponse getUserRegistrationDetails(String registrationCode) { SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_RETRIEVE_API); - return response; - } + UserRegistration userRegistration = null; + try { + userRegistration = getUserRegistrationDocument(new HashMap() { + { + put("registrationCode", registrationCode); + } + }); + + } catch (Exception e) { + LOGGER.error(String.format("Exception in %s : %s", "getUserRegistrationDetails", e.getMessage())); + } + + if (userRegistration != null) { + response.put(Constants.RESULT, userRegistration); + } else { + response.getParams().setStatus(Constants.FAILED); + response.getParams().setErrmsg("Failed to get response"); + response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); + } - public SBApiResponse getDeptDetails() { - SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_DEPT_INFO_API); return response; } @@ -137,6 +161,24 @@ private String validateRegisterationPayload(UserRegistrationInfo userRegInfo) { return StringUtils.EMPTY; } + private UserRegistration getUserRegistrationDocument(Map mustMatch) throws Exception { + UserRegistration userRegistration = null; + SearchSourceBuilder searchSourceBuilder = queryBuilder(mustMatch); + SearchResponse searchResponse = indexerService.getEsResult(serverProperties.getUserRegistrationIndex(), + serverProperties.getEsProfileIndexType(), searchSourceBuilder); + + if (searchResponse.getHits().totalHits > 0) { + SearchHit[] searchHit = searchResponse.getHits().getHits(); + + for (SearchHit hit : searchHit) { + Map sourceObj = hit.getSourceAsMap(); + userRegistration = mapper.convertValue(sourceObj, UserRegistration.class); + } + } + + return userRegistration; + } + private UserRegistration getRegistrationObject(UserRegistrationInfo userRegInfo) { UserRegistration userRegistration = new UserRegistration(); userRegistration.setFirstName(userRegInfo.getFirstName()); @@ -147,11 +189,16 @@ private UserRegistration getRegistrationObject(UserRegistrationInfo userRegInfo) userRegistration.setPosition(userRegInfo.getPosition()); userRegistration.setSource(userRegInfo.getSource()); - userRegistration.setRegistrationCode(serverProperties.getUserRegistrationCode() + "-" - + userRegInfo.getDeptName() + "-" + RandomStringUtils.random(15, Boolean.TRUE, Boolean.TRUE)); - userRegistration.setId(RandomStringUtils.random(15, Boolean.TRUE, Boolean.TRUE)); - userRegistration.setStatus(UserRegistrationStatus.INITIATED.name()); - userRegistration.setCreatedOn(new Date().getTime()); + if (StringUtils.isBlank(userRegInfo.getRegistrationCode())) { + userRegistration.setRegistrationCode(serverProperties.getUserRegCodePrefix() + "-" + + userRegInfo.getDeptName() + "-" + RandomStringUtils.random(6, Boolean.TRUE, Boolean.TRUE)); + userRegistration.setId(RandomStringUtils.random(15, Boolean.TRUE, Boolean.TRUE)); + userRegistration.setCreatedOn(new Date().getTime()); + } else { + userRegistration.setUpdatedOn(new Date().getTime()); + } + userRegistration.setStatus(UserRegistrationStatus.CREATED.name()); + return userRegistration; } diff --git a/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java b/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java index 339a99ffd..70c0beb54 100644 --- a/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java +++ b/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java @@ -8,7 +8,7 @@ */ public enum UserRegistrationStatus { - INITIATED(0), CREATED(1), APPROVED(2), DENIED(3), FAILED(4); + CREATED(1), WF_INITIATED(2), WF_APPROVED(3), WF_DENIED(4), FAILED(5); private int status = 0; diff --git a/src/main/java/org/sunbird/user/registration/util/Utility.java b/src/main/java/org/sunbird/user/registration/util/Utility.java index 5d727c352..71dad8d4b 100644 --- a/src/main/java/org/sunbird/user/registration/util/Utility.java +++ b/src/main/java/org/sunbird/user/registration/util/Utility.java @@ -1,9 +1,23 @@ package org.sunbird.user.registration.util; +import java.util.Arrays; +import java.util.List; import java.util.regex.Pattern; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.sunbird.common.util.CbExtServerProperties; + +@Service public class Utility { + static CbExtServerProperties serverProperties; + + @Autowired + Utility(CbExtServerProperties serverProperties) { + this.serverProperties = serverProperties; + } + /** * Check the email id is valid or not * @@ -16,7 +30,11 @@ public static Boolean emailValidation(String email) { + "A-Z]{2,7}$"; Pattern pat = Pattern.compile(emailRegex); - return (email == null) ? Boolean.FALSE : pat.matcher(email).matches(); + if (pat.matcher(email).matches()) { + List domainList = Arrays.asList(serverProperties.getUserRegistrationDomain().split(",")); + return domainList.contains(email.split("@")[1]); + } + return Boolean.FALSE; } diff --git a/src/main/java/org/sunbird/workallocation/service/AllocationService.java b/src/main/java/org/sunbird/workallocation/service/AllocationService.java index 3335e16d8..c82f11170 100644 --- a/src/main/java/org/sunbird/workallocation/service/AllocationService.java +++ b/src/main/java/org/sunbird/workallocation/service/AllocationService.java @@ -29,6 +29,7 @@ import org.sunbird.common.service.PdfGenerationService; import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; +import org.sunbird.common.util.IndexerService; import org.sunbird.core.exception.BadRequestException; import org.sunbird.workallocation.model.*; import org.sunbird.workallocation.util.FRACReqBuilder; diff --git a/src/main/java/org/sunbird/workallocation/service/AllocationServiceV2.java b/src/main/java/org/sunbird/workallocation/service/AllocationServiceV2.java index aee28625b..290d16374 100644 --- a/src/main/java/org/sunbird/workallocation/service/AllocationServiceV2.java +++ b/src/main/java/org/sunbird/workallocation/service/AllocationServiceV2.java @@ -43,6 +43,7 @@ import org.sunbird.common.service.OutboundRequestHandlerServiceImpl; import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; +import org.sunbird.common.util.IndexerService; import org.sunbird.core.exception.ApplicationLogicError; import org.sunbird.core.exception.BadRequestException; import org.sunbird.core.producer.Producer; diff --git a/src/main/java/org/sunbird/workallocation/util/Validator.java b/src/main/java/org/sunbird/workallocation/util/Validator.java index 0b298da75..00c838c23 100644 --- a/src/main/java/org/sunbird/workallocation/util/Validator.java +++ b/src/main/java/org/sunbird/workallocation/util/Validator.java @@ -5,12 +5,12 @@ import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; +import org.sunbird.common.util.IndexerService; import org.sunbird.core.exception.BadRequestException; import org.sunbird.workallocation.model.SearchCriteria; import org.sunbird.workallocation.model.WorkAllocationDTO; import org.sunbird.workallocation.model.WorkAllocationDTOV2; import org.sunbird.workallocation.model.WorkOrderDTO; -import org.sunbird.workallocation.service.IndexerService; import java.util.Arrays; import java.util.List; diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index c77676e08..8d2c89bb6 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -176,4 +176,5 @@ sunbird_sso_client_secret=e9899c3c-bf7f-4bc8-972b-959a1d2e3d57 accesstoken.publickey.basepath=/home/juhi/keys/U2JTvZDDV8xo7fk_4wuc-d5Rf64OLmhziQEHcGnUshM user.assessment.submission.duration=120 -user.registration.code=iGOT +user.registration.code.prefix=iGOT +user.registration.domain=yopmail.com,google.com From 531d1b0e99c94a55ede4925cbff86d26b423d2a3 Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Mon, 30 May 2022 16:51:26 +0530 Subject: [PATCH 05/22] Added getDeptDetails API --- .../common/util/CbExtServerProperties.java | 10 ++ .../department/model/DeptPublicInfo.java | 39 ++---- .../UserRegistrationController.java | 6 + .../service/UserRegistrationService.java | 14 ++- .../service/UserRegistrationServiceImpl.java | 114 ++++++++++++++---- src/main/resources/application.properties | 16 ++- 6 files changed, 137 insertions(+), 62 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index b856185e8..f6e70dd90 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -240,6 +240,9 @@ public class CbExtServerProperties { @Value("${user.registration.domain}") private String userRegistrationDomain; + @Value("${user.registration.dept.exclude.list}") + private String userRegistrationDeptExcludeList; + public String getUserAssessmentSubmissionDuration() { return userAssessmentSubmissionDuration; } @@ -875,4 +878,11 @@ public void setUserRegistrationDomain(String userRegistrationDomain) { this.userRegistrationDomain = userRegistrationDomain; } + public void setUserRegistrationDeptExcludeList(String userRegistrationDeptExcludeList) { + this.userRegistrationDeptExcludeList = userRegistrationDeptExcludeList; + } + + public List getUserRegistrationDeptExcludeList() { + return Arrays.asList(userRegistrationDeptExcludeList.split(",", -1)); + } } \ No newline at end of file diff --git a/src/main/java/org/sunbird/portal/department/model/DeptPublicInfo.java b/src/main/java/org/sunbird/portal/department/model/DeptPublicInfo.java index 36475960b..11d9e3498 100644 --- a/src/main/java/org/sunbird/portal/department/model/DeptPublicInfo.java +++ b/src/main/java/org/sunbird/portal/department/model/DeptPublicInfo.java @@ -1,40 +1,27 @@ package org.sunbird.portal.department.model; public class DeptPublicInfo { - int id; - String root_org; - String friendly_name; - String description; + private String identifier; + private String channel; - public int getId() { - return id; + public DeptPublicInfo(String identifier, String channel) { + this.identifier = identifier; + this.channel = channel; } - public void setId(int id) { - this.id = id; + public String getIdentifier() { + return identifier; } - public String getRoot_org() { - return root_org; + public void setIdentifier(String identifier) { + this.identifier = identifier; } - public void setRoot_org(String root_org) { - this.root_org = root_org; + public String getChannel() { + return channel; } - public String getFriendly_name() { - return friendly_name; - } - - public void setFriendly_name(String friendly_name) { - this.friendly_name = friendly_name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; + public void setChannel(String channel) { + this.channel = channel; } } diff --git a/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java b/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java index 002073ff5..ffc277582 100644 --- a/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java +++ b/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java @@ -34,4 +34,10 @@ public ResponseEntity getUserRegistrationDetails(@RequestParam St SBApiResponse response = userRegService.getUserRegistrationDetails(regCode); return new ResponseEntity<>(response, response.getResponseCode()); } + + @GetMapping("/user/registration/v1/getDeptDetails") + public ResponseEntity getDeptDetails() throws Exception { + SBApiResponse response = userRegService.getDeptDetails(); + return new ResponseEntity<>(response, response.getResponseCode()); + } } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java index abb438fcb..bacd08ef4 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java @@ -13,8 +13,7 @@ public interface UserRegistrationService { /** * Registers the given user and creates WorkFlow Service request for approval. * - * @param userRegInfo - * - User Registration Information + * @param userRegInfo - User Registration Information * @return - Returns the API Response object which contains success / failure * message */ @@ -24,11 +23,18 @@ public interface UserRegistrationService { * Retrieves the User Registration Code details if exists for the given * Registration Code value. * - * @param registrationCode - * - Registration Code which used to identify the object + * @param registrationCode - Registration Code which used to identify the object * @return - Returns the API Response object which contains success / failure * message */ public SBApiResponse getUserRegistrationDetails(String registrationCode); + /** + * Retrieves the department details which can be provided user to select upon + * while creating Register request + * + * @return - Returns the API response object which contains success / failure + * message + */ + public SBApiResponse getDeptDetails(); } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index 929a48b49..bfcfccb1a 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -1,8 +1,12 @@ package org.sunbird.user.registration.service; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.UUID; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; @@ -19,11 +23,16 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.sunbird.common.model.SBApiResponse; +import org.sunbird.common.model.SunbirdApiResp; +import org.sunbird.common.model.SunbirdApiRespContent; import org.sunbird.common.model.SunbirdApiRespParam; +import org.sunbird.common.model.SunbirdApiResultResponse; +import org.sunbird.common.service.OutboundRequestHandlerServiceImpl; import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; import org.sunbird.common.util.IndexerService; import org.sunbird.core.producer.Producer; +import org.sunbird.portal.department.model.DeptPublicInfo; import org.sunbird.user.registration.model.UserRegistration; import org.sunbird.user.registration.model.UserRegistrationInfo; import org.sunbird.user.registration.util.UserRegistrationStatus; @@ -47,9 +56,11 @@ public class UserRegistrationServiceImpl implements UserRegistrationService { @Autowired Producer kafkaProducer; + @Autowired + OutboundRequestHandlerServiceImpl outboundRequestHandlerService; + @Override public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { - SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_REGISTER_API); String payloadvalidation = validateRegisterationPayload(userRegInfo); if (StringUtils.isBlank(payloadvalidation)) { @@ -60,8 +71,8 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { put(Constants.EMAIL, userRegInfo.getEmail()); } }); - if (regDocument == null || (regDocument.getStatus().equals(UserRegistrationStatus.FAILED.name()) - && regDocument.getRegistrationCode().equals(regDocument.getRegistrationCode()))) { + if (regDocument == null + || UserRegistrationStatus.FAILED.name().equalsIgnoreCase(regDocument.getStatus())) { // create the doc in ES UserRegistration userRegistration = getRegistrationObject(userRegInfo); if (StringUtils.isBlank(userRegistration.getId())) { @@ -74,11 +85,10 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { // fire Kafka topic event kafkaProducer.push(serverProperties.getUserRegistrationTopic(), userRegistration); response.setResponseCode(HttpStatus.ACCEPTED); + response.getResult().put(Constants.RESULT, userRegistration); } } else { - payloadvalidation = regDocument.getStatus().equals(UserRegistrationStatus.FAILED.name()) - ? "Registration code is missing" - : "Email id already exists"; + payloadvalidation = "Email id already exists"; } } catch (Exception e) { @@ -110,7 +120,7 @@ public SBApiResponse getUserRegistrationDetails(String registrationCode) { } if (userRegistration != null) { - response.put(Constants.RESULT, userRegistration); + response.getResult().put(Constants.RESULT, userRegistration); } else { response.getParams().setStatus(Constants.FAILED); response.getParams().setErrmsg("Failed to get response"); @@ -120,6 +130,57 @@ public SBApiResponse getUserRegistrationDetails(String registrationCode) { return response; } + public SBApiResponse getDeptDetails() { + SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_DEPT_INFO_API); + + try { + List orgList = new ArrayList<>(); + int count = 0; + int iterateCount = 0; + do { + // request body + Map requestMap = new HashMap<>(); + requestMap.put(Constants.OFFSET, iterateCount); + requestMap.put(Constants.LIMIT, 100); + requestMap.put(Constants.FIELDS, + new ArrayList<>(Arrays.asList(Constants.CHANNEL, Constants.IDENTIFIER))); + requestMap.put(Constants.FILTERS, new HashMap() { + { + put(Constants.IS_TENANT, Boolean.TRUE); + } + }); + + String serviceURL = serverProperties.getSbUrl() + serverProperties.getSbOrgSearchPath(); + SunbirdApiResp orgResponse = mapper.convertValue( + outboundRequestHandlerService.fetchResultUsingPost(serviceURL, new HashMap() { + { + put(Constants.REQUEST, requestMap); + } + }), SunbirdApiResp.class); + + SunbirdApiResultResponse resultResp = orgResponse.getResult().getResponse(); + count = resultResp.getCount(); + iterateCount = iterateCount + resultResp.getContent().size(); + List excludeList = serverProperties.getUserRegistrationDeptExcludeList(); + for (SunbirdApiRespContent content : resultResp.getContent()) { + if (!excludeList.isEmpty() && excludeList.contains(content.getIdentifier())) { + orgList.add(new DeptPublicInfo(content.getIdentifier(), content.getChannel())); + } + } + } while (count != iterateCount); + + response.getResult().put("count", orgList.size()); + response.getResult().put("content", orgList); + + } catch (Exception e) { + LOGGER.error("Exception occurred in getDeptDetails", e); + response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); + response.getParams().setErrmsg("Exception occurred in getDeptDetails. Exception: " + e.getMessage()); + } + + return response; + } + private SBApiResponse createDefaultResponse(String api) { SBApiResponse response = new SBApiResponse(); response.setId(api); @@ -132,51 +193,53 @@ private SBApiResponse createDefaultResponse(String api) { } private String validateRegisterationPayload(UserRegistrationInfo userRegInfo) { + StringBuffer str = new StringBuffer(); + List errList = new ArrayList(); if (StringUtils.isBlank(userRegInfo.getFirstName())) { - return "Firstname missing"; + errList.add("FirstName"); } if (StringUtils.isBlank(userRegInfo.getLastName())) { - return "Lastname missing"; + errList.add("LastName"); } if (StringUtils.isBlank(userRegInfo.getEmail())) { - return "Email missing"; + errList.add("Email"); } if (StringUtils.isBlank(userRegInfo.getDeptId())) { - return "Department Id missing"; + errList.add("DeptId"); } if (StringUtils.isBlank(userRegInfo.getDeptName())) { - return "Department name missing"; + errList.add("Department"); } if (StringUtils.isBlank(userRegInfo.getPosition())) { - return "Position missing"; + errList.add("Position"); } if (StringUtils.isBlank(userRegInfo.getSource())) { - return "Source missing"; + errList.add("Source"); + } + if (!errList.isEmpty()) { + str.append("Failed to Register User Details. Missing Params - [").append(errList.toString()).append("]"); } // email Validation if (!Utility.emailValidation(userRegInfo.getEmail())) { - return "Invalid email id"; + str.setLength(0); + str.append("Invalid email id"); } + return str.toString(); - return StringUtils.EMPTY; } private UserRegistration getUserRegistrationDocument(Map mustMatch) throws Exception { - UserRegistration userRegistration = null; SearchSourceBuilder searchSourceBuilder = queryBuilder(mustMatch); SearchResponse searchResponse = indexerService.getEsResult(serverProperties.getUserRegistrationIndex(), serverProperties.getEsProfileIndexType(), searchSourceBuilder); if (searchResponse.getHits().totalHits > 0) { + // Record already exists. will return the existing one. SearchHit[] searchHit = searchResponse.getHits().getHits(); - - for (SearchHit hit : searchHit) { - Map sourceObj = hit.getSourceAsMap(); - userRegistration = mapper.convertValue(sourceObj, UserRegistration.class); - } + return mapper.convertValue(searchHit[0], UserRegistration.class); } - return userRegistration; + return null; } private UserRegistration getRegistrationObject(UserRegistrationInfo userRegInfo) { @@ -192,7 +255,7 @@ private UserRegistration getRegistrationObject(UserRegistrationInfo userRegInfo) if (StringUtils.isBlank(userRegInfo.getRegistrationCode())) { userRegistration.setRegistrationCode(serverProperties.getUserRegCodePrefix() + "-" + userRegInfo.getDeptName() + "-" + RandomStringUtils.random(6, Boolean.TRUE, Boolean.TRUE)); - userRegistration.setId(RandomStringUtils.random(15, Boolean.TRUE, Boolean.TRUE)); + userRegistration.setId(UUID.randomUUID().toString()); userRegistration.setCreatedOn(new Date().getTime()); } else { userRegistration.setUpdatedOn(new Date().getTime()); @@ -205,8 +268,7 @@ private UserRegistration getRegistrationObject(UserRegistrationInfo userRegInfo) /** * Elasticsearch must match bool search query builder * - * @param mustMatch - * Map + * @param mustMatch Map * @return SearchSourceBuilder */ private SearchSourceBuilder queryBuilder(Map mustMatch) { diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8d2c89bb6..3437b601b 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -32,7 +32,7 @@ lms.user.read.path=private/user/v1/read/ lms.user.update.path=private/user/v1/update progress.api.endpoint=v1/content/state/read participants.api.endpoint=v1/batch/participants/list -sb.api.key=bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJRekw4VVA1dUtqUFdaZVpMd1ZtTFJvNHdqWTg2a2FrcSJ9.TPjV0xLacSbp3FbJ7XeqHoKFN35Rl4YHx3DZNN9pm0o +sb.api.key=apiKey #Elastic search config @@ -44,7 +44,6 @@ es.password= es.profile.index=userprofile es.profile.index.type=_doc es.profile.source.fields=photo,id,employmentDetails,personalDetails -es.user.registration.index=user-registration #workallocation es config @@ -62,7 +61,6 @@ kafka.topics.wat.telemetry.event=watTelemetryTopic kafka.topics.parent.telemetry.event=dev.telemetry.raw kafka.topics.parent.rating.event = dev.rating.event kafka.topics.userutility.telemetry.event=userLastLoginTopic -kafka.topics.user.registration.register.event=userRegistration userutility.telemetry.event.pdata.id=dev.sunbird.cb.ext.service userutility.telemetry.event.pdata.pid=sunbird-cb-ext-service @@ -170,11 +168,17 @@ sunbird_sso_password=admin sunbird_sso_url=https://igot-dev.in/auth/ sunbird_sso_realm=sunbird sso.password=admin -sunbird_sso_publickey=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoBa+pmsxpPhGED2/zexM/PL+rLv2YnLCbX2agY2fllucCvnPNmWRTyg8L+qgkJBpHuhcHqXEFTfBm2WCe4yke+0LnGi6SGsCJTrc2Sh+Lgo/L9r1lr7uOoD8BHE6ywnbHG2ok7qyomCTD9LpG1WXFk4T3WUH9+gN2vm77s3YJz2yfo2UlMd1Dp9nWZhfwB1vwJLuRHnqEKkSH8M2K8SFRdpgOyLdM9fprr7Ebgr7SWdoAy2q3mUONSmDsftKDeEWjr6MXGTATfbMfKE3GFqddMjFHkmvh42aM+RlU3N2xo2msF8M2sYF6YlIDkED+9h+y0QROJjQlBr774GAd06I0wIDAQAB +sunbird_sso_publickey=publicKey sso.username=admin -sunbird_sso_client_secret=e9899c3c-bf7f-4bc8-972b-959a1d2e3d57 -accesstoken.publickey.basepath=/home/juhi/keys/U2JTvZDDV8xo7fk_4wuc-d5Rf64OLmhziQEHcGnUshM +sunbird_sso_client_secret=clientSecretValue +accesstoken.publickey.basepath=publicKeyPath user.assessment.submission.duration=120 +#User Registration Feature user.registration.code.prefix=iGOT user.registration.domain=yopmail.com,google.com +es.user.registration.index=user-registration +kafka.topics.user.registration.register.event=user.register.event +#Provide Dept Id as comma separated values here to exclude the details +user.registration.dept.exclude.list=01,02 + From 30eed4b327866e8fffcf81da7821204a837dda4f Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Mon, 30 May 2022 18:31:58 +0530 Subject: [PATCH 06/22] Fix for user registration --- .../service/UserRegistrationServiceImpl.java | 20 +++++++++++-------- src/main/resources/application.properties | 2 +- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index bfcfccb1a..578e0be1f 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -62,8 +62,8 @@ public class UserRegistrationServiceImpl implements UserRegistrationService { @Override public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_REGISTER_API); - String payloadvalidation = validateRegisterationPayload(userRegInfo); - if (StringUtils.isBlank(payloadvalidation)) { + String errMsg = validateRegisterationPayload(userRegInfo); + if (StringUtils.isBlank(errMsg)) { try { // verify the given email exist in ES Server UserRegistration regDocument = getUserRegistrationDocument(new HashMap() { @@ -86,18 +86,22 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { kafkaProducer.push(serverProperties.getUserRegistrationTopic(), userRegistration); response.setResponseCode(HttpStatus.ACCEPTED); response.getResult().put(Constants.RESULT, userRegistration); + } else { + response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); + response.getParams().setErrmsg("Failed to add details to ES Service"); } } else { - payloadvalidation = "Email id already exists"; + errMsg = "Email id already exists"; } } catch (Exception e) { LOGGER.error(String.format("Exception in %s : %s", "registerUser", e.getMessage())); + errMsg = "Failed to process message. Exception: " + e.getMessage(); } } - if (StringUtils.isNotBlank(payloadvalidation)) { + if (StringUtils.isNotBlank(errMsg)) { response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg(payloadvalidation); + response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.BAD_REQUEST); } @@ -141,7 +145,7 @@ public SBApiResponse getDeptDetails() { // request body Map requestMap = new HashMap<>(); requestMap.put(Constants.OFFSET, iterateCount); - requestMap.put(Constants.LIMIT, 100); + requestMap.put(Constants.LIMIT, 1000); requestMap.put(Constants.FIELDS, new ArrayList<>(Arrays.asList(Constants.CHANNEL, Constants.IDENTIFIER))); requestMap.put(Constants.FILTERS, new HashMap() { @@ -163,7 +167,7 @@ public SBApiResponse getDeptDetails() { iterateCount = iterateCount + resultResp.getContent().size(); List excludeList = serverProperties.getUserRegistrationDeptExcludeList(); for (SunbirdApiRespContent content : resultResp.getContent()) { - if (!excludeList.isEmpty() && excludeList.contains(content.getIdentifier())) { + if (!excludeList.isEmpty() && !excludeList.contains(content.getIdentifier())) { orgList.add(new DeptPublicInfo(content.getIdentifier(), content.getChannel())); } } @@ -220,7 +224,7 @@ private String validateRegisterationPayload(UserRegistrationInfo userRegInfo) { str.append("Failed to Register User Details. Missing Params - [").append(errList.toString()).append("]"); } // email Validation - if (!Utility.emailValidation(userRegInfo.getEmail())) { + if (StringUtils.isNotBlank(userRegInfo.getEmail()) && !Utility.emailValidation(userRegInfo.getEmail())) { str.setLength(0); str.append("Invalid email id"); } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3437b601b..3d1ba28f0 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -177,7 +177,7 @@ user.assessment.submission.duration=120 #User Registration Feature user.registration.code.prefix=iGOT user.registration.domain=yopmail.com,google.com -es.user.registration.index=user-registration +es.user.registration.index=user_registration kafka.topics.user.registration.register.event=user.register.event #Provide Dept Id as comma separated values here to exclude the details user.registration.dept.exclude.list=01,02 From 66e9dae674a9dae6fcfe73e001c2aefcf0e28ca1 Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Tue, 31 May 2022 09:49:57 +0530 Subject: [PATCH 07/22] Fix for user search against ES --- .../org/sunbird/common/util/Constants.java | 3 + .../service/UserRegistrationServiceImpl.java | 115 ++++++++++++------ src/main/resources/application.properties | 2 +- 3 files changed, 84 insertions(+), 36 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/Constants.java b/src/main/java/org/sunbird/common/util/Constants.java index 41e34eb9d..996f2519e 100644 --- a/src/main/java/org/sunbird/common/util/Constants.java +++ b/src/main/java/org/sunbird/common/util/Constants.java @@ -388,6 +388,9 @@ public class Constants { public static final String USER_REGISTRATION_UPDATE_API = "api.user.registration.update"; public static final String USER_REGISTRATION_RETRIEVE_API = "api.user.registration.retrieve"; public static final String USER_REGISTRATION_DEPT_INFO_API = "api.user.registration.dept.info"; + public static final String COUNT = "count"; + + public static final String EMAIL_EXIST_ERROR = "Email id already registered"; public static final String API_VERSION_1 = "1.0"; diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index 578e0be1f..36479e070 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -22,7 +22,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; import org.sunbird.common.model.SBApiResponse; +import org.sunbird.common.model.SunbirdApiRequest; import org.sunbird.common.model.SunbirdApiResp; import org.sunbird.common.model.SunbirdApiRespContent; import org.sunbird.common.model.SunbirdApiRespParam; @@ -31,6 +33,7 @@ import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; import org.sunbird.common.util.IndexerService; +import org.sunbird.core.exception.ApplicationLogicError; import org.sunbird.core.producer.Producer; import org.sunbird.portal.department.model.DeptPublicInfo; import org.sunbird.user.registration.model.UserRegistration; @@ -59,41 +62,48 @@ public class UserRegistrationServiceImpl implements UserRegistrationService { @Autowired OutboundRequestHandlerServiceImpl outboundRequestHandlerService; + @Autowired + RestTemplate restTemplate; + @Override public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_REGISTER_API); String errMsg = validateRegisterationPayload(userRegInfo); if (StringUtils.isBlank(errMsg)) { try { - // verify the given email exist in ES Server - UserRegistration regDocument = getUserRegistrationDocument(new HashMap() { - { - put(Constants.EMAIL, userRegInfo.getEmail()); - } - }); - if (regDocument == null - || UserRegistrationStatus.FAILED.name().equalsIgnoreCase(regDocument.getStatus())) { - // create the doc in ES - UserRegistration userRegistration = getRegistrationObject(userRegInfo); - if (StringUtils.isBlank(userRegistration.getId())) { - userRegistration.setId(regDocument.getId()); - } - RestStatus status = indexerService.addEntity(serverProperties.getUserRegistrationIndex(), - serverProperties.getEsProfileIndexType(), userRegistration.getId(), - mapper.convertValue(userRegistration, Map.class)); - if (status.equals(RestStatus.CREATED)) { - // fire Kafka topic event - kafkaProducer.push(serverProperties.getUserRegistrationTopic(), userRegistration); - response.setResponseCode(HttpStatus.ACCEPTED); - response.getResult().put(Constants.RESULT, userRegistration); + if (isUserExist(userRegInfo.getEmail().toLowerCase())) { + errMsg = Constants.EMAIL_EXIST_ERROR; + } else { + // verify the given email exist in ES Server + UserRegistration regDocument = getUserRegistrationDocument(new HashMap() { + { + put(Constants.EMAIL, userRegInfo.getEmail()); + } + }); + + if (regDocument == null + || UserRegistrationStatus.FAILED.name().equalsIgnoreCase(regDocument.getStatus())) { + // create the doc in ES + UserRegistration userRegistration = getRegistrationObject(userRegInfo); + if (StringUtils.isBlank(userRegistration.getId())) { + userRegistration.setId(regDocument.getId()); + } + RestStatus status = indexerService.addEntity(serverProperties.getUserRegistrationIndex(), + serverProperties.getEsProfileIndexType(), userRegistration.getId(), + mapper.convertValue(userRegistration, Map.class)); + if (status.equals(RestStatus.CREATED)) { + // fire Kafka topic event + kafkaProducer.push(serverProperties.getUserRegistrationTopic(), userRegistration); + response.setResponseCode(HttpStatus.ACCEPTED); + response.getResult().put(Constants.RESULT, userRegistration); + } else { + response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); + response.getParams().setErrmsg("Failed to add details to ES Service"); + } } else { - response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); - response.getParams().setErrmsg("Failed to add details to ES Service"); + errMsg = Constants.EMAIL_EXIST_ERROR; } - } else { - errMsg = "Email id already exists"; } - } catch (Exception e) { LOGGER.error(String.format("Exception in %s : %s", "registerUser", e.getMessage())); errMsg = "Failed to process message. Exception: " + e.getMessage(); @@ -233,14 +243,12 @@ private String validateRegisterationPayload(UserRegistrationInfo userRegInfo) { } private UserRegistration getUserRegistrationDocument(Map mustMatch) throws Exception { - SearchSourceBuilder searchSourceBuilder = queryBuilder(mustMatch); SearchResponse searchResponse = indexerService.getEsResult(serverProperties.getUserRegistrationIndex(), - serverProperties.getEsProfileIndexType(), searchSourceBuilder); + serverProperties.getEsProfileIndexType(), queryBuilder(mustMatch)); - if (searchResponse.getHits().totalHits > 0) { - // Record already exists. will return the existing one. - SearchHit[] searchHit = searchResponse.getHits().getHits(); - return mapper.convertValue(searchHit[0], UserRegistration.class); + if (searchResponse.getHits().getTotalHits() > 0) { + SearchHit hit = searchResponse.getHits().getAt(0); + return mapper.convertValue(hit.getSourceAsMap(), UserRegistration.class); } return null; @@ -277,10 +285,47 @@ private UserRegistration getRegistrationObject(UserRegistrationInfo userRegInfo) */ private SearchSourceBuilder queryBuilder(Map mustMatch) { BoolQueryBuilder boolBuilder = new BoolQueryBuilder(); - SearchSourceBuilder searchBuilder = new SearchSourceBuilder().query(boolBuilder); + for (Map.Entry entry : mustMatch.entrySet()) { - boolBuilder.must(QueryBuilders.matchQuery(entry.getKey() + ".keyword", entry.getValue())); + boolBuilder.must(QueryBuilders.termQuery(entry.getKey() + ".raw", entry.getValue())); + } + return new SearchSourceBuilder().query(boolBuilder); + } + + private boolean isUserExist(String email) { + // request body + SunbirdApiRequest requestObj = new SunbirdApiRequest(); + Map reqMap = new HashMap<>(); + reqMap.put(Constants.FILTERS, new HashMap() { + { + put(Constants.EMAIL, email); + } + }); + requestObj.setRequest(reqMap); + + HashMap headersValue = new HashMap<>(); + headersValue.put(Constants.CONTENT_TYPE, "application/json"); + headersValue.put(Constants.AUTHORIZATION, serverProperties.getSbApiKey()); + + try { + String url = serverProperties.getSbUrl() + serverProperties.getUserSearchEndPoint(); + + Map response = outboundRequestHandlerService.fetchResultUsingPost(url, requestObj, + headersValue); + if (response != null && "OK".equalsIgnoreCase((String) response.get("responseCode"))) { + Map map = (Map) response.get("result"); + if (map.get("response") != null) { + Map responseObj = (Map) map.get("response"); + int count = (int) responseObj.get(Constants.COUNT); + if (count == 0) + return false; + else + return true; + } + } + } catch (Exception e) { + throw new ApplicationLogicError("Sunbird Service ERROR: ", e); } - return searchBuilder; + return true; } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3d1ba28f0..8f568ac6c 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -180,5 +180,5 @@ user.registration.domain=yopmail.com,google.com es.user.registration.index=user_registration kafka.topics.user.registration.register.event=user.register.event #Provide Dept Id as comma separated values here to exclude the details -user.registration.dept.exclude.list=01,02 +user.registration.dept.exclude.list=0133334975707217922 From d3dad47277ac62a033e453b9c3731fc08a99cf9b Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Wed, 1 Jun 2022 07:17:59 +0530 Subject: [PATCH 08/22] Updated WF request --- .../sunbird/common/util/CbExtServerProperties.java | 11 +++++++++++ .../service/UserRegistrationConsumer.java | 10 +++++----- src/main/resources/application.properties | 2 +- 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index f6e70dd90..86cf75149 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -242,6 +242,9 @@ public class CbExtServerProperties { @Value("${user.registration.dept.exclude.list}") private String userRegistrationDeptExcludeList; + + @Value("${user.registration.workflow.service.name}") + private String userRegistrationWorkFlowServiceName; public String getUserAssessmentSubmissionDuration() { return userAssessmentSubmissionDuration; @@ -885,4 +888,12 @@ public void setUserRegistrationDeptExcludeList(String userRegistrationDeptExclud public List getUserRegistrationDeptExcludeList() { return Arrays.asList(userRegistrationDeptExcludeList.split(",", -1)); } + + public String getUserRegistrationWorkFlowServiceName() { + return userRegistrationWorkFlowServiceName; + } + + public void setUserRegistrationWorkFlowServiceName(String userRegistrationWorkFlowServiceName) { + this.userRegistrationWorkFlowServiceName = userRegistrationWorkFlowServiceName; + } } \ No newline at end of file diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index 88ec9ab61..7d3a45851 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -5,6 +5,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.UUID; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.elasticsearch.rest.RestStatus; @@ -91,19 +92,18 @@ public void processMessage(ConsumerRecord data) { PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT)); } - } - } private WfRequest wfRequestObj(UserRegistration userRegistration) { WfRequest wfRequest = new WfRequest(); wfRequest.setState(userRegistration.getStatus()); wfRequest.setAction(userRegistration.getStatus()); - wfRequest.setUserId("1234"); - wfRequest.setActorUserId("1234"); + String uuid = UUID.randomUUID().toString(); + wfRequest.setUserId(uuid); + wfRequest.setActorUserId(uuid); wfRequest.setApplicationId(userRegistration.getId()); - wfRequest.setServiceName("user-registration"); + wfRequest.setServiceName(serverProperties.getUserRegistrationWorkFlowServiceName()); wfRequest.setUpdateFieldValues(Arrays.asList(new HashMap<>())); return wfRequest; } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8f568ac6c..8f303f141 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -181,4 +181,4 @@ es.user.registration.index=user_registration kafka.topics.user.registration.register.event=user.register.event #Provide Dept Id as comma separated values here to exclude the details user.registration.dept.exclude.list=0133334975707217922 - +user.registration.workflow.service.name=user_registration From 77bbd5640f8db2db6841a2b8999c3229ff8e3198 Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Wed, 1 Jun 2022 09:56:37 +0530 Subject: [PATCH 09/22] Updated WF request details --- .../user/registration/service/UserRegistrationConsumer.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index 7d3a45851..bee58f66f 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -97,12 +97,13 @@ public void processMessage(ConsumerRecord data) { private WfRequest wfRequestObj(UserRegistration userRegistration) { WfRequest wfRequest = new WfRequest(); - wfRequest.setState(userRegistration.getStatus()); - wfRequest.setAction(userRegistration.getStatus()); + wfRequest.setState(Constants.INITIATE); + wfRequest.setAction(Constants.INITIATE); String uuid = UUID.randomUUID().toString(); wfRequest.setUserId(uuid); wfRequest.setActorUserId(uuid); wfRequest.setApplicationId(userRegistration.getId()); + wfRequest.setDeptName(userRegistration.getDeptName()); wfRequest.setServiceName(serverProperties.getUserRegistrationWorkFlowServiceName()); wfRequest.setUpdateFieldValues(Arrays.asList(new HashMap<>())); return wfRequest; From 294a160498a31fade8fbff8c3a1d59fbe52e6cf5 Mon Sep 17 00:00:00 2001 From: nivetha Date: Wed, 1 Jun 2022 11:58:52 +0530 Subject: [PATCH 10/22] Registration notification --- .../org/sunbird/common/util/Constants.java | 8 +- .../service/UserRegistrationConsumer.java | 95 ++++++++++++------- 2 files changed, 68 insertions(+), 35 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/Constants.java b/src/main/java/org/sunbird/common/util/Constants.java index 996f2519e..5e5c7659f 100644 --- a/src/main/java/org/sunbird/common/util/Constants.java +++ b/src/main/java/org/sunbird/common/util/Constants.java @@ -344,7 +344,6 @@ public class Constants { public static final String IS_DELETED = "isDeleted"; public static final String EXCLUDE_USER_EMAILS = "exclude_user_emails"; public static final String INCOMPLETE_COURSES = "incompletecourses"; - public static final String SUBJECT_ = "subject"; public static final String POSTER_IMAGE = "posterImage"; public static final String COURSE_URL = "course.url"; @@ -389,7 +388,12 @@ public class Constants { public static final String USER_REGISTRATION_RETRIEVE_API = "api.user.registration.retrieve"; public static final String USER_REGISTRATION_DEPT_INFO_API = "api.user.registration.dept.info"; public static final String COUNT = "count"; - + + // email params + public static final String TITLE = "title"; + public static final String DESCRIPTION = "description"; + public static final String TEMPLATE = "template"; + public static final String EMAIL_EXIST_ERROR = "Email id already registered"; public static final String API_VERSION_1 = "1.0"; diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index bee58f66f..d0a4c5842 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -23,6 +23,7 @@ import org.sunbird.common.util.PropertiesCache; import org.sunbird.user.registration.model.UserRegistration; import org.sunbird.user.registration.model.WfRequest; +import org.sunbird.user.registration.util.UserRegistrationStatus; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; @@ -79,20 +80,15 @@ public void processMessage(ConsumerRecord data) { serverProperties.getEsProfileIndexType(), userRegistration.getId(), mapper.convertValue(userRegistration, Map.class)); - if (status.equals(RestStatus.CREATED)) { - // send notification - List sendTo = new ArrayList() { - { - add(userRegistration.getEmail()); - } - }; - Map params = notificationPayload(); - notificationUtil.sendNotification(sendTo, params, - PropertiesCache.getInstance().getProperty(Constants.SENDER_MAIL), - PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) - + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT)); + if (!status.equals(RestStatus.CREATED)) { + LOGGER.info("Failed to update registration status for the document id : " + + userRegistration.getRegistrationCode() + "and status : " + userRegistration.getStatus()); } + } else { + userRegistration.setStatus(UserRegistrationStatus.FAILED.name()); } + // send notification + sendNotification(userRegistration); } private WfRequest wfRequestObj(UserRegistration userRegistration) { @@ -129,32 +125,65 @@ private Map workflowTransition(WfRequest wfRequest) { return null; } - private Map notificationPayload() { - Map notificationObj = new HashMap<>(); - notificationObj.put("mode", "email"); - notificationObj.put("deliveryType", "message"); - notificationObj.put("config", new HashMap() { + private void sendNotification(UserRegistration userRegistration) { + List sendTo = new ArrayList() { { - put("sender", ""); - put("subject", ""); + add(userRegistration.getEmail()); } - }); - notificationObj.put("ids", new ArrayList() { - { - add(""); - } - }); - notificationObj.put("template", new HashMap() { + }; + + Map notificationObj = new HashMap<>(); + notificationObj.put("mode", Constants.EMAIL); + notificationObj.put("deliveryType", Constants.MESSAGE); + notificationObj.put("config", new HashMap() { { - put("data", ""); - put("params", new HashMap() { - { - put("", ""); - } - }); + put(Constants.SUBJECT, "iGOT - Registration"); } }); - return notificationObj; + notificationObj.put("ids", sendTo); + notificationObj.put(Constants.TEMPLATE, + notificationMessage(userRegistration.getStatus(), userRegistration.getRegistrationCode())); + + if (notificationObj.get(Constants.TEMPLATE) != null) { + notificationUtil.sendNotification(sendTo, notificationObj, + PropertiesCache.getInstance().getProperty(Constants.SENDER_MAIL), + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) + + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT)); + } + } + + private Map notificationMessage(String status, String regCode) { + Map template = new HashMap<>(); + template.put(Constants.ID, "user-registration"); + Map params = new HashMap<>(); + template.put("params", params); + switch (status) { + case "WF_INITIATED": + params.put(Constants.TITLE, "Thankyou for registering in iGOT!"); + params.put(Constants.STATUS, "Your request is initiated."); + params.put(Constants.DESCRIPTION, "Please use the code " + regCode + " for further process."); + break; + case "WF_APPROVED": + params.put(Constants.TITLE, "iGOT registration approved"); + params.put(Constants.STATUS, "Your request is approved and your account is active now."); + params.put(Constants.DESCRIPTION, "Click on the below link to set your password and explore iGOT."); + params.put("btn-url", "https://igot-dev.in"); + params.put("btn-name", "Click here"); + break; + case "WF_DENIED": + params.put(Constants.TITLE, "iGOT registration denied"); + params.put(Constants.STATUS, "Your request is denied"); + break; + case "FAILED": + params.put(Constants.TITLE, "iGOT registration failed"); + params.put(Constants.STATUS, "Your registration request is failed. Please try again later."); + break; + + default: + template = null; + break; + } + return template; } } From 5b90e742c30e55c68cf903aba9ad7afa647fa302 Mon Sep 17 00:00:00 2001 From: nivetha Date: Wed, 1 Jun 2022 12:02:32 +0530 Subject: [PATCH 11/22] Registration notification changes --- .../user/registration/service/UserRegistrationConsumer.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index d0a4c5842..84f0563e3 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -161,7 +161,8 @@ private Map notificationMessage(String status, String regCode) { case "WF_INITIATED": params.put(Constants.TITLE, "Thankyou for registering in iGOT!"); params.put(Constants.STATUS, "Your request is initiated."); - params.put(Constants.DESCRIPTION, "Please use the code " + regCode + " for further process."); + params.put(Constants.DESCRIPTION, + "Please use the code " + "" + regCode + "" + " for further process."); break; case "WF_APPROVED": params.put(Constants.TITLE, "iGOT registration approved"); From 9245c51af01cd1294985eb8ba5bbf68ae94699d3 Mon Sep 17 00:00:00 2001 From: nivetha Date: Wed, 1 Jun 2022 13:57:15 +0530 Subject: [PATCH 12/22] registration notification - params config --- .../common/util/CbExtServerProperties.java | 91 ++++++++++++++++++- .../org/sunbird/common/util/Constants.java | 1 + .../service/UserRegistrationConsumer.java | 24 ++--- src/main/resources/application.properties | 9 ++ 4 files changed, 110 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index 86cf75149..872f2580f 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -242,10 +242,34 @@ public class CbExtServerProperties { @Value("${user.registration.dept.exclude.list}") private String userRegistrationDeptExcludeList; - + @Value("${user.registration.workflow.service.name}") private String userRegistrationWorkFlowServiceName; + @Value("${user.registration.subject}") + private String userRegistrationSubject; + + @Value("${user.registration.title}") + private String userRegistrationTitle; + + @Value("${user.registration.status}") + private String userRegistrationStatus; + + @Value("${user.registration.thankyou.message}") + private String userRegistrationThankyouMessage; + + @Value("${user.registration.initiated.message}") + private String userRegistrationInitiatedMessage; + + @Value("${user.registration.approved.message}") + private String userRegistrationApprovedMessage; + + @Value("${user.registration.failed.message}") + private String userRegistrationFailedMessage; + + @Value("${user.registeration.route.button.name}") + private String userRegisterationButtonName; + public String getUserAssessmentSubmissionDuration() { return userAssessmentSubmissionDuration; } @@ -896,4 +920,69 @@ public String getUserRegistrationWorkFlowServiceName() { public void setUserRegistrationWorkFlowServiceName(String userRegistrationWorkFlowServiceName) { this.userRegistrationWorkFlowServiceName = userRegistrationWorkFlowServiceName; } + + public String getUserRegistrationTitle() { + return userRegistrationTitle; + } + + public void setUserRegistrationTitle(String userRegistrationTitle) { + this.userRegistrationTitle = userRegistrationTitle; + } + + public String getUserRegistrationStatus() { + return userRegistrationStatus; + } + + public void setUserRegistrationStatus(String userRegistrationStatus) { + this.userRegistrationStatus = userRegistrationStatus; + } + + public String getUserRegistrationThankyouMessage() { + return userRegistrationThankyouMessage; + } + + public void setUserRegistrationThankyouMessage(String userRegistrationThankyouMessage) { + this.userRegistrationThankyouMessage = userRegistrationThankyouMessage; + } + + public String getUserRegistrationInitiatedMessage() { + return userRegistrationInitiatedMessage; + } + + public void setUserRegistrationInitiatedMessage(String userRegistrationInitiatedMessage) { + this.userRegistrationInitiatedMessage = userRegistrationInitiatedMessage; + } + + public String getUserRegistrationApprovedMessage() { + return userRegistrationApprovedMessage; + } + + public void setUserRegistrationApprovedMessage(String userRegistrationApprovedMessage) { + this.userRegistrationApprovedMessage = userRegistrationApprovedMessage; + } + + public String getUserRegistrationFailedMessage() { + return userRegistrationFailedMessage; + } + + public void setUserRegistrationFailedMessage(String userRegistrationFailedMessage) { + this.userRegistrationFailedMessage = userRegistrationFailedMessage; + } + + public String getUserRegisterationButtonName() { + return userRegisterationButtonName; + } + + public void setUserRegisterationButtonName(String userRegisterationButtonName) { + this.userRegisterationButtonName = userRegisterationButtonName; + } + + public String getUserRegistrationSubject() { + return userRegistrationSubject; + } + + public void setUserRegistrationSubject(String userRegistrationSubject) { + this.userRegistrationSubject = userRegistrationSubject; + } + } \ No newline at end of file diff --git a/src/main/java/org/sunbird/common/util/Constants.java b/src/main/java/org/sunbird/common/util/Constants.java index 5e5c7659f..856f9dd24 100644 --- a/src/main/java/org/sunbird/common/util/Constants.java +++ b/src/main/java/org/sunbird/common/util/Constants.java @@ -393,6 +393,7 @@ public class Constants { public static final String TITLE = "title"; public static final String DESCRIPTION = "description"; public static final String TEMPLATE = "template"; + public static final String USER_REGISTERATION_TEMPLATE = "user-registration"; public static final String EMAIL_EXIST_ERROR = "Email id already registered"; diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index 84f0563e3..c710868bf 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -137,7 +137,7 @@ private void sendNotification(UserRegistration userRegistration) { notificationObj.put("deliveryType", Constants.MESSAGE); notificationObj.put("config", new HashMap() { { - put(Constants.SUBJECT, "iGOT - Registration"); + put(Constants.SUBJECT, serverProperties.getUserRegistrationSubject()); } }); notificationObj.put("ids", sendTo); @@ -154,30 +154,26 @@ private void sendNotification(UserRegistration userRegistration) { private Map notificationMessage(String status, String regCode) { Map template = new HashMap<>(); - template.put(Constants.ID, "user-registration"); + template.put(Constants.ID, Constants.USER_REGISTERATION_TEMPLATE); Map params = new HashMap<>(); + params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", status)); + params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", status)); template.put("params", params); switch (status) { case "WF_INITIATED": - params.put(Constants.TITLE, "Thankyou for registering in iGOT!"); - params.put(Constants.STATUS, "Your request is initiated."); - params.put(Constants.DESCRIPTION, - "Please use the code " + "" + regCode + "" + " for further process."); + params.put(Constants.TITLE, serverProperties.getUserRegistrationThankyouMessage()); + params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationInitiatedMessage() + .replace("{regCode}", "" + regCode + "")); break; case "WF_APPROVED": - params.put(Constants.TITLE, "iGOT registration approved"); - params.put(Constants.STATUS, "Your request is approved and your account is active now."); - params.put(Constants.DESCRIPTION, "Click on the below link to set your password and explore iGOT."); + params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationApprovedMessage()); params.put("btn-url", "https://igot-dev.in"); - params.put("btn-name", "Click here"); + params.put("btn-name", serverProperties.getUserRegisterationButtonName()); break; case "WF_DENIED": - params.put(Constants.TITLE, "iGOT registration denied"); - params.put(Constants.STATUS, "Your request is denied"); break; case "FAILED": - params.put(Constants.TITLE, "iGOT registration failed"); - params.put(Constants.STATUS, "Your registration request is failed. Please try again later."); + params.put(Constants.STATUS, serverProperties.getUserRegistrationFailedMessage()); break; default: diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8f303f141..61b4d0c5d 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -182,3 +182,12 @@ kafka.topics.user.registration.register.event=user.register.event #Provide Dept Id as comma separated values here to exclude the details user.registration.dept.exclude.list=0133334975707217922 user.registration.workflow.service.name=user_registration +#Registration email template message +user.registration.subject=iGOT-Registeration +user.registration.title=iGOT registration {status} +user.registration.status=Your registration request is {status}. +user.registration.thankyou.message=Thankyou for registering in iGOT! +user.registration.initiated.message=Please use the code {regCode} for further process. +user.registration.approved.message=Click on the below link to set your password and explore iGOT. +user.registration.failed.message=Please try again later. +user.registeration.route.button.name=Click here From a012ee29971a6f4172c7297aff17f6e177e22e12 Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Wed, 1 Jun 2022 17:35:27 +0530 Subject: [PATCH 13/22] Added handling for error cases --- .../common/util/CbExtServerProperties.java | 10 +++++ .../registration/model/UserRegistration.java | 9 ----- .../service/UserRegistrationConsumer.java | 38 ++++++++++++------ .../service/UserRegistrationServiceImpl.java | 39 ++++++++++--------- src/main/resources/application.properties | 2 + 5 files changed, 59 insertions(+), 39 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index 872f2580f..20c70e5eb 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -269,6 +269,9 @@ public class CbExtServerProperties { @Value("${user.registeration.route.button.name}") private String userRegisterationButtonName; + + @Value("${user.registration.domain.name}") + private String userRegistrationDomainName; public String getUserAssessmentSubmissionDuration() { return userAssessmentSubmissionDuration; @@ -985,4 +988,11 @@ public void setUserRegistrationSubject(String userRegistrationSubject) { this.userRegistrationSubject = userRegistrationSubject; } + public String getUserRegistrationDomainName() { + return userRegistrationDomainName; + } + + public void setUserRegistrationDomainName(String userRegistrationDomainName) { + this.userRegistrationDomainName = userRegistrationDomainName; + } } \ No newline at end of file diff --git a/src/main/java/org/sunbird/user/registration/model/UserRegistration.java b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java index 89490ad35..3c8ac9f19 100644 --- a/src/main/java/org/sunbird/user/registration/model/UserRegistration.java +++ b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java @@ -7,7 +7,6 @@ * */ public class UserRegistration extends UserRegistrationInfo { - private String id; private String wfId; private String priviousStatus; private String status; @@ -16,14 +15,6 @@ public class UserRegistration extends UserRegistrationInfo { private String createdBy; private String updatedBy; - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - public String getWfId() { return wfId; } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index c710868bf..aa41466ac 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -49,7 +49,8 @@ public class UserRegistrationConsumer { @Autowired IndexerService indexerService; - @KafkaListener(id = "id1", groupId = "userRegistrationTopic-consumer", topicPartitions = { + @SuppressWarnings("unchecked") + @KafkaListener(topicPartitions = { @TopicPartition(topic = "${kafka.topics.user.registration.register.event}", partitions = { "0", "1", "2", "3" }) }) public void processMessage(ConsumerRecord data) { @@ -76,21 +77,36 @@ public void processMessage(ConsumerRecord data) { List wfIds = (List) wfTransitionData.get("wfIds"); userRegistration.setStatus((String) wfTransitionData.get(Constants.STATUS)); userRegistration.setWfId(wfIds.get(0)); - RestStatus status = indexerService.addEntity(serverProperties.getUserRegistrationIndex(), - serverProperties.getEsProfileIndexType(), userRegistration.getId(), - mapper.convertValue(userRegistration, Map.class)); - - if (!status.equals(RestStatus.CREATED)) { - LOGGER.info("Failed to update registration status for the document id : " - + userRegistration.getRegistrationCode() + "and status : " + userRegistration.getStatus()); - } } else { userRegistration.setStatus(UserRegistrationStatus.FAILED.name()); } + RestStatus status = indexerService.updateEntity(serverProperties.getUserRegistrationIndex(), + serverProperties.getEsProfileIndexType(), userRegistration.getRegistrationCode(), + mapper.convertValue(userRegistration, Map.class)); + + LOGGER.info("Successfully called ES update request. REST Status ? " + (status != null ? status.name() : null)); + + if (!RestStatus.OK.equals(status)) { + LOGGER.info("Failed to update registration status for the document id : " + + userRegistration.getRegistrationCode() + "and status : " + userRegistration.getStatus()); + } // send notification sendNotification(userRegistration); } + @KafkaListener(topicPartitions = { + @TopicPartition(topic = "${kafka.topics.user.registration.createUser}", partitions = { "0", "1", "2", + "3" }) }) + public void processCreateUserMessage(ConsumerRecord data) { + try { + WfRequest wfRequest = gson.fromJson(data.value(), WfRequest.class); + LOGGER.info("Consumed Request in Topic to create user in registration:: " + + mapper.writeValueAsString(wfRequest)); + } catch (Exception e) { + LOGGER.error("Failed to process message in Topic to create user in registration.", e); + } + } + private WfRequest wfRequestObj(UserRegistration userRegistration) { WfRequest wfRequest = new WfRequest(); wfRequest.setState(Constants.INITIATE); @@ -98,7 +114,7 @@ private WfRequest wfRequestObj(UserRegistration userRegistration) { String uuid = UUID.randomUUID().toString(); wfRequest.setUserId(uuid); wfRequest.setActorUserId(uuid); - wfRequest.setApplicationId(userRegistration.getId()); + wfRequest.setApplicationId(userRegistration.getRegistrationCode()); wfRequest.setDeptName(userRegistration.getDeptName()); wfRequest.setServiceName(serverProperties.getUserRegistrationWorkFlowServiceName()); wfRequest.setUpdateFieldValues(Arrays.asList(new HashMap<>())); @@ -167,7 +183,7 @@ private Map notificationMessage(String status, String regCode) { break; case "WF_APPROVED": params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationApprovedMessage()); - params.put("btn-url", "https://igot-dev.in"); + params.put("btn-url", serverProperties.getUserRegistrationDomainName()); params.put("btn-name", serverProperties.getUserRegisterationButtonName()); break; case "WF_DENIED": diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index 36479e070..dfce1ef72 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -6,7 +6,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.UUID; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; @@ -83,19 +82,25 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { if (regDocument == null || UserRegistrationStatus.FAILED.name().equalsIgnoreCase(regDocument.getStatus())) { - // create the doc in ES - UserRegistration userRegistration = getRegistrationObject(userRegInfo); - if (StringUtils.isBlank(userRegistration.getId())) { - userRegistration.setId(regDocument.getId()); + // create / update the doc in ES + RestStatus status = null; + if(regDocument == null) { + regDocument = getRegistrationObject(userRegInfo); + status = indexerService.addEntity(serverProperties.getUserRegistrationIndex(), + serverProperties.getEsProfileIndexType(), regDocument.getRegistrationCode(), + mapper.convertValue(regDocument, Map.class)); + } else { + regDocument.setStatus(UserRegistrationStatus.CREATED.name()); + status = indexerService.updateEntity(serverProperties.getUserRegistrationIndex(), + serverProperties.getEsProfileIndexType(), regDocument.getRegistrationCode(), + mapper.convertValue(regDocument, Map.class)); } - RestStatus status = indexerService.addEntity(serverProperties.getUserRegistrationIndex(), - serverProperties.getEsProfileIndexType(), userRegistration.getId(), - mapper.convertValue(userRegistration, Map.class)); - if (status.equals(RestStatus.CREATED)) { + + if (status.equals(RestStatus.CREATED) || status.equals(RestStatus.OK)) { // fire Kafka topic event - kafkaProducer.push(serverProperties.getUserRegistrationTopic(), userRegistration); + kafkaProducer.push(serverProperties.getUserRegistrationTopic(), regDocument); response.setResponseCode(HttpStatus.ACCEPTED); - response.getResult().put(Constants.RESULT, userRegistration); + response.getResult().put(Constants.RESULT, regDocument); } else { response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); response.getParams().setErrmsg("Failed to add details to ES Service"); @@ -123,12 +128,9 @@ public SBApiResponse getUserRegistrationDetails(String registrationCode) { SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_RETRIEVE_API); UserRegistration userRegistration = null; try { - userRegistration = getUserRegistrationDocument(new HashMap() { - { - put("registrationCode", registrationCode); - } - }); - + Map esObject = indexerService.readEntity(serverProperties.getUserRegistrationIndex(), + serverProperties.getEsProfileIndexType(), registrationCode); + userRegistration = mapper.convertValue(esObject, UserRegistration.class); } catch (Exception e) { LOGGER.error(String.format("Exception in %s : %s", "getUserRegistrationDetails", e.getMessage())); } @@ -266,8 +268,7 @@ private UserRegistration getRegistrationObject(UserRegistrationInfo userRegInfo) if (StringUtils.isBlank(userRegInfo.getRegistrationCode())) { userRegistration.setRegistrationCode(serverProperties.getUserRegCodePrefix() + "-" - + userRegInfo.getDeptName() + "-" + RandomStringUtils.random(6, Boolean.TRUE, Boolean.TRUE)); - userRegistration.setId(UUID.randomUUID().toString()); + + userRegInfo.getDeptName() + "-" + RandomStringUtils.random(8, Boolean.TRUE, Boolean.TRUE)); userRegistration.setCreatedOn(new Date().getTime()); } else { userRegistration.setUpdatedOn(new Date().getTime()); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 61b4d0c5d..3abaa2c17 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -179,6 +179,7 @@ user.registration.code.prefix=iGOT user.registration.domain=yopmail.com,google.com es.user.registration.index=user_registration kafka.topics.user.registration.register.event=user.register.event +kafka.topics.user.registration.createUser=workflow.user.registration.createUser #Provide Dept Id as comma separated values here to exclude the details user.registration.dept.exclude.list=0133334975707217922 user.registration.workflow.service.name=user_registration @@ -191,3 +192,4 @@ user.registration.initiated.message=Please use the code {regCode} for further pr user.registration.approved.message=Click on the below link to set your password and explore iGOT. user.registration.failed.message=Please try again later. user.registeration.route.button.name=Click here +user.registration.domain.name=https://igot-dev.in/ From e748e969bcfd090863c8cd4d826841ad70a65c08 Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Thu, 2 Jun 2022 09:13:04 +0530 Subject: [PATCH 14/22] Added handling for user create flow, auto approval for specific domain. --- .../common/util/CbExtServerProperties.java | 28 ++++++- .../service/UserRegistrationConsumer.java | 70 ++-------------- .../UserRegistrationNotificationService.java | 16 ++++ ...erRegistrationNotificationServiceImpl.java | 84 +++++++++++++++++++ .../service/UserRegistrationService.java | 7 ++ .../service/UserRegistrationServiceImpl.java | 58 +++++++++++-- .../user/registration/util/Utility.java | 41 --------- .../user/service/UserUtilityService.java | 8 ++ .../user/service/UserUtilityServiceImpl.java | 27 +++++- src/main/resources/application.properties | 3 +- 10 files changed, 229 insertions(+), 113 deletions(-) create mode 100644 src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java create mode 100644 src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java delete mode 100644 src/main/java/org/sunbird/user/registration/util/Utility.java diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index 20c70e5eb..f01666b5e 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -236,6 +236,9 @@ public class CbExtServerProperties { @Value("${kafka.topics.user.registration.register.event}") private String userRegistrationTopic; + + @Value("${kafka.topics.user.registration.createUser}") + private String userRegistrationCreateUserTopic; @Value("${user.registration.domain}") private String userRegistrationDomain; @@ -273,6 +276,11 @@ public class CbExtServerProperties { @Value("${user.registration.domain.name}") private String userRegistrationDomainName; + @Value("${user.registration.preApproved.domain}") + private String userRegistrationPreApprovedDomainList; + + + public String getUserAssessmentSubmissionDuration() { return userAssessmentSubmissionDuration; } @@ -899,9 +907,17 @@ public String getUserRegistrationTopic() { public void setUserRegistrationTopic(String userRegistrationTopic) { this.userRegistrationTopic = userRegistrationTopic; } + + public String getUserRegistrationCreateUserTopic() { + return userRegistrationCreateUserTopic; + } - public String getUserRegistrationDomain() { - return userRegistrationDomain; + public void setUserRegistrationCreateUserTopic(String userRegistrationCreateUserTopic) { + this.userRegistrationCreateUserTopic = userRegistrationCreateUserTopic; + } + + public List getUserRegistrationDomain() { + return Arrays.asList(userRegistrationDomain.split(",", -1)); } public void setUserRegistrationDomain(String userRegistrationDomain) { @@ -995,4 +1011,12 @@ public String getUserRegistrationDomainName() { public void setUserRegistrationDomainName(String userRegistrationDomainName) { this.userRegistrationDomainName = userRegistrationDomainName; } + + public List getUserRegistrationPreApprovedDomainList() { + return Arrays.asList(userRegistrationPreApprovedDomainList.split(",", -1)); + } + + public void setUserRegistrationPreApprovedDomainList(String userRegistrationPreApprovedDomainList) { + this.userRegistrationPreApprovedDomainList = userRegistrationPreApprovedDomainList; + } } \ No newline at end of file diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index aa41466ac..ff7dd593e 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -1,6 +1,5 @@ package org.sunbird.user.registration.service; -import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -20,7 +19,6 @@ import org.sunbird.common.util.Constants; import org.sunbird.common.util.IndexerService; import org.sunbird.common.util.NotificationUtil; -import org.sunbird.common.util.PropertiesCache; import org.sunbird.user.registration.model.UserRegistration; import org.sunbird.user.registration.model.WfRequest; import org.sunbird.user.registration.util.UserRegistrationStatus; @@ -49,6 +47,12 @@ public class UserRegistrationConsumer { @Autowired IndexerService indexerService; + @Autowired + UserRegistrationService userRegService; + + @Autowired + UserRegistrationNotificationService userRegNotificationService; + @SuppressWarnings("unchecked") @KafkaListener(topicPartitions = { @TopicPartition(topic = "${kafka.topics.user.registration.register.event}", partitions = { "0", "1", "2", @@ -91,7 +95,7 @@ public void processMessage(ConsumerRecord data) { + userRegistration.getRegistrationCode() + "and status : " + userRegistration.getStatus()); } // send notification - sendNotification(userRegistration); + userRegNotificationService.sendNotification(userRegistration); } @KafkaListener(topicPartitions = { @@ -102,6 +106,7 @@ public void processCreateUserMessage(ConsumerRecord data) { WfRequest wfRequest = gson.fromJson(data.value(), WfRequest.class); LOGGER.info("Consumed Request in Topic to create user in registration:: " + mapper.writeValueAsString(wfRequest)); + userRegService.initiateCreateUserFlow(wfRequest.getApplicationId()); } catch (Exception e) { LOGGER.error("Failed to process message in Topic to create user in registration.", e); } @@ -140,63 +145,4 @@ private Map workflowTransition(WfRequest wfRequest) { } return null; } - - private void sendNotification(UserRegistration userRegistration) { - List sendTo = new ArrayList() { - { - add(userRegistration.getEmail()); - } - }; - - Map notificationObj = new HashMap<>(); - notificationObj.put("mode", Constants.EMAIL); - notificationObj.put("deliveryType", Constants.MESSAGE); - notificationObj.put("config", new HashMap() { - { - put(Constants.SUBJECT, serverProperties.getUserRegistrationSubject()); - } - }); - notificationObj.put("ids", sendTo); - notificationObj.put(Constants.TEMPLATE, - notificationMessage(userRegistration.getStatus(), userRegistration.getRegistrationCode())); - - if (notificationObj.get(Constants.TEMPLATE) != null) { - notificationUtil.sendNotification(sendTo, notificationObj, - PropertiesCache.getInstance().getProperty(Constants.SENDER_MAIL), - PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) - + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT)); - } - } - - private Map notificationMessage(String status, String regCode) { - Map template = new HashMap<>(); - template.put(Constants.ID, Constants.USER_REGISTERATION_TEMPLATE); - Map params = new HashMap<>(); - params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", status)); - params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", status)); - template.put("params", params); - switch (status) { - case "WF_INITIATED": - params.put(Constants.TITLE, serverProperties.getUserRegistrationThankyouMessage()); - params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationInitiatedMessage() - .replace("{regCode}", "" + regCode + "")); - break; - case "WF_APPROVED": - params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationApprovedMessage()); - params.put("btn-url", serverProperties.getUserRegistrationDomainName()); - params.put("btn-name", serverProperties.getUserRegisterationButtonName()); - break; - case "WF_DENIED": - break; - case "FAILED": - params.put(Constants.STATUS, serverProperties.getUserRegistrationFailedMessage()); - break; - - default: - template = null; - break; - } - return template; - } - } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java new file mode 100644 index 000000000..0b7e4357c --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java @@ -0,0 +1,16 @@ +package org.sunbird.user.registration.service; + +import org.springframework.stereotype.Service; +import org.sunbird.user.registration.model.UserRegistration; + +/** + * Provides APIs to send out notification for user registration + * + * @author karthik + * + */ +@Service +public interface UserRegistrationNotificationService { + + public void sendNotification(UserRegistration userRegistration); +} diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java new file mode 100644 index 000000000..bbcccaede --- /dev/null +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java @@ -0,0 +1,84 @@ +package org.sunbird.user.registration.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.beans.factory.annotation.Autowired; +import org.sunbird.common.util.CbExtServerProperties; +import org.sunbird.common.util.Constants; +import org.sunbird.common.util.NotificationUtil; +import org.sunbird.common.util.PropertiesCache; +import org.sunbird.user.registration.model.UserRegistration; + +public class UserRegistrationNotificationServiceImpl implements UserRegistrationNotificationService { + + @Autowired + CbExtServerProperties serverProperties; + + @Autowired + NotificationUtil notificationUtil; + + @Override + public void sendNotification(UserRegistration userRegistration) { + List sendTo = new ArrayList() { + private static final long serialVersionUID = 1L; + + { + add(userRegistration.getEmail()); + } + }; + + Map notificationObj = new HashMap<>(); + notificationObj.put("mode", Constants.EMAIL); + notificationObj.put("deliveryType", Constants.MESSAGE); + notificationObj.put("config", new HashMap() { + { + put(Constants.SUBJECT, serverProperties.getUserRegistrationSubject()); + } + }); + notificationObj.put("ids", sendTo); + notificationObj.put(Constants.TEMPLATE, + notificationMessage(userRegistration.getStatus(), userRegistration.getRegistrationCode())); + + if (notificationObj.get(Constants.TEMPLATE) != null) { + notificationUtil.sendNotification(sendTo, notificationObj, + PropertiesCache.getInstance().getProperty(Constants.SENDER_MAIL), + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) + + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT)); + } + } + + private Map notificationMessage(String status, String regCode) { + Map template = new HashMap<>(); + template.put(Constants.ID, Constants.USER_REGISTERATION_TEMPLATE); + Map params = new HashMap<>(); + params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", status)); + params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", status)); + template.put("params", params); + switch (status) { + case "WF_INITIATED": + params.put(Constants.TITLE, serverProperties.getUserRegistrationThankyouMessage()); + params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationInitiatedMessage() + .replace("{regCode}", "" + regCode + "")); + break; + case "WF_APPROVED": + params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationApprovedMessage()); + params.put("btn-url", serverProperties.getUserRegistrationDomainName()); + params.put("btn-name", serverProperties.getUserRegisterationButtonName()); + break; + case "WF_DENIED": + break; + case "FAILED": + params.put(Constants.STATUS, serverProperties.getUserRegistrationFailedMessage()); + break; + + default: + template = null; + break; + } + return template; + } + +} diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java index bacd08ef4..9e53f0c69 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationService.java @@ -37,4 +37,11 @@ public interface UserRegistrationService { * message */ public SBApiResponse getDeptDetails(); + + /** + * Initiates the User Registration process + * + * @param registrationCode - User Registration Code + */ + public void initiateCreateUserFlow(String registrationCode); } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index dfce1ef72..8c41b583d 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -6,6 +6,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.regex.Pattern; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; @@ -38,7 +39,7 @@ import org.sunbird.user.registration.model.UserRegistration; import org.sunbird.user.registration.model.UserRegistrationInfo; import org.sunbird.user.registration.util.UserRegistrationStatus; -import org.sunbird.user.registration.util.Utility; +import org.sunbird.user.service.UserUtilityService; import com.fasterxml.jackson.databind.ObjectMapper; @@ -64,6 +65,9 @@ public class UserRegistrationServiceImpl implements UserRegistrationService { @Autowired RestTemplate restTemplate; + @Autowired + UserUtilityService userUtilityService; + @Override public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_REGISTER_API); @@ -75,6 +79,7 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { } else { // verify the given email exist in ES Server UserRegistration regDocument = getUserRegistrationDocument(new HashMap() { + private static final long serialVersionUID = 1L; { put(Constants.EMAIL, userRegInfo.getEmail()); } @@ -84,7 +89,7 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { || UserRegistrationStatus.FAILED.name().equalsIgnoreCase(regDocument.getStatus())) { // create / update the doc in ES RestStatus status = null; - if(regDocument == null) { + if (regDocument == null) { regDocument = getRegistrationObject(userRegInfo); status = indexerService.addEntity(serverProperties.getUserRegistrationIndex(), serverProperties.getEsProfileIndexType(), regDocument.getRegistrationCode(), @@ -95,10 +100,15 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { serverProperties.getEsProfileIndexType(), regDocument.getRegistrationCode(), mapper.convertValue(regDocument, Map.class)); } - + if (status.equals(RestStatus.CREATED) || status.equals(RestStatus.OK)) { - // fire Kafka topic event - kafkaProducer.push(serverProperties.getUserRegistrationTopic(), regDocument); + if (isPreApprovedDomain(regDocument.getEmail())) { + // Fire createUser event + kafkaProducer.push(serverProperties.getUserRegistrationCreateUserTopic(), regDocument); + } else { + // Fire register event + kafkaProducer.push(serverProperties.getUserRegistrationTopic(), regDocument); + } response.setResponseCode(HttpStatus.ACCEPTED); response.getResult().put(Constants.RESULT, regDocument); } else { @@ -197,6 +207,19 @@ public SBApiResponse getDeptDetails() { return response; } + public void initiateCreateUserFlow(String registrationCode) { + try { + /** + * 1. Create User 2. Read created User 3. Update User 4. Create NodeBB user Id + * 5. Assign Role 6. Reset Password and get activation link + */ + LOGGER.info("Initiated User Creation flow for Reg. Code :: " + registrationCode); + + } catch (Exception e) { + LOGGER.error("Failed to process user create flow.", e); + } + } + private SBApiResponse createDefaultResponse(String api) { SBApiResponse response = new SBApiResponse(); response.setId(api); @@ -236,7 +259,7 @@ private String validateRegisterationPayload(UserRegistrationInfo userRegInfo) { str.append("Failed to Register User Details. Missing Params - [").append(errList.toString()).append("]"); } // email Validation - if (StringUtils.isNotBlank(userRegInfo.getEmail()) && !Utility.emailValidation(userRegInfo.getEmail())) { + if (StringUtils.isNotBlank(userRegInfo.getEmail()) && !emailValidation(userRegInfo.getEmail())) { str.setLength(0); str.append("Invalid email id"); } @@ -329,4 +352,27 @@ private boolean isUserExist(String email) { } return true; } + + /** + * Check the email id is valid or not + * + * @param email String + * @return Boolean + */ + public Boolean emailValidation(String email) { + String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\." + "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + + "A-Z]{2,7}$"; + Boolean retValue = Boolean.FALSE; + Pattern pat = Pattern.compile(emailRegex); + if (pat.matcher(email).matches()) { + String emailDomain = email.split("@")[1]; + retValue = serverProperties.getUserRegistrationDomain().contains(emailDomain) + || serverProperties.getUserRegistrationPreApprovedDomainList().contains(emailDomain); + } + return retValue; + } + + private Boolean isPreApprovedDomain(String email) { + return serverProperties.getUserRegistrationPreApprovedDomainList().contains(email.split("@")[1]); + } } diff --git a/src/main/java/org/sunbird/user/registration/util/Utility.java b/src/main/java/org/sunbird/user/registration/util/Utility.java deleted file mode 100644 index 71dad8d4b..000000000 --- a/src/main/java/org/sunbird/user/registration/util/Utility.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.sunbird.user.registration.util; - -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.sunbird.common.util.CbExtServerProperties; - -@Service -public class Utility { - - static CbExtServerProperties serverProperties; - - @Autowired - Utility(CbExtServerProperties serverProperties) { - this.serverProperties = serverProperties; - } - - /** - * Check the email id is valid or not - * - * @param email - * String - * @return Boolean - */ - public static Boolean emailValidation(String email) { - String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\." + "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" - + "A-Z]{2,7}$"; - - Pattern pat = Pattern.compile(emailRegex); - if (pat.matcher(email).matches()) { - List domainList = Arrays.asList(serverProperties.getUserRegistrationDomain().split(",")); - return domainList.contains(email.split("@")[1]); - } - return Boolean.FALSE; - - } - -} diff --git a/src/main/java/org/sunbird/user/service/UserUtilityService.java b/src/main/java/org/sunbird/user/service/UserUtilityService.java index a94eab3b6..3db496faa 100644 --- a/src/main/java/org/sunbird/user/service/UserUtilityService.java +++ b/src/main/java/org/sunbird/user/service/UserUtilityService.java @@ -4,6 +4,7 @@ import java.util.Map; import org.sunbird.telemetry.model.LastLoginInfo; +import org.sunbird.user.registration.model.UserRegistration; public interface UserUtilityService { @@ -19,4 +20,11 @@ public interface UserUtilityService { Map getUsersReadData(String userId, String authToken, String X_authToken); + boolean createUser(UserRegistration userRegistration); + + boolean updateUser(UserRegistration userRegistration); + + String getActivationLink(UserRegistration userRegistration); + + boolean createNodeBBUser(UserRegistration userRegistration); } \ No newline at end of file diff --git a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java index 4076cc88c..259ddff99 100644 --- a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java +++ b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java @@ -25,6 +25,7 @@ import org.sunbird.core.exception.ApplicationLogicError; import org.sunbird.core.logger.CbExtLogger; import org.sunbird.telemetry.model.LastLoginInfo; +import org.sunbird.user.registration.model.UserRegistration; import org.sunbird.user.util.TelemetryUtils; import com.fasterxml.jackson.databind.ObjectMapper; @@ -60,7 +61,7 @@ public class UserUtilityServiceImpl implements UserUtilityService { public boolean validateUser(String userId) { return validateUser(StringUtils.EMPTY, userId); } - + @Override public boolean validateUser(String rootOrg, String userId) { @@ -202,4 +203,28 @@ public Map getUsersReadData(String userId, String authToken, Str Map responseMap = (Map) result.get(Constants.RESPONSE); return responseMap; } + + @Override + public boolean createUser(UserRegistration userRegistration) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean updateUser(UserRegistration userRegistration) { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getActivationLink(UserRegistration userRegistration) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean createNodeBBUser(UserRegistration userRegistration) { + // TODO Auto-generated method stub + return false; + } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3abaa2c17..e8468bfe4 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -176,7 +176,8 @@ user.assessment.submission.duration=120 #User Registration Feature user.registration.code.prefix=iGOT -user.registration.domain=yopmail.com,google.com +user.registration.preApproved.domain=yopmail.com +user.registration.domain=gmail.com es.user.registration.index=user_registration kafka.topics.user.registration.register.event=user.register.event kafka.topics.user.registration.createUser=workflow.user.registration.createUser From 47024e5a8fa68667c8883cf0e67423a37b97726b Mon Sep 17 00:00:00 2001 From: nivetha Date: Thu, 2 Jun 2022 12:38:15 +0530 Subject: [PATCH 15/22] Fixed registration notification --- .../sunbird/common/util/NotificationUtil.java | 28 ++++++++++++++++++ .../UserRegistrationNotificationService.java | 1 - ...erRegistrationNotificationServiceImpl.java | 29 ++++++++++++++----- .../util/UserRegistrationStatus.java | 11 +++++-- 4 files changed, 59 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/NotificationUtil.java b/src/main/java/org/sunbird/common/util/NotificationUtil.java index 9e82c19ba..65a65e7cd 100644 --- a/src/main/java/org/sunbird/common/util/NotificationUtil.java +++ b/src/main/java/org/sunbird/common/util/NotificationUtil.java @@ -2,6 +2,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; @@ -20,6 +21,9 @@ public class NotificationUtil { public static final Logger Logger; private static final String EXCEPTION = "Exception in Send Notification %s"; + + @Autowired + RestTemplate restTemplate; static { Logger = LoggerFactory.getLogger(NotificationUtil.class); @@ -49,4 +53,28 @@ public void sendNotification(List sendTo, Map }).start(); } + public void sendNotification(List> notifications) { + new Thread(() -> { + try { + String notificationUrl = PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) + + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT); + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + Map notificationRequest = new HashMap<>(); + notificationRequest.put(Constants.REQUEST, new HashMap() { + { + put(Constants.NOTIFICATIONS, notifications); + } + }); + + HttpEntity req = new HttpEntity<>(notificationRequest, headers); + Logger.info(String.format("Notification Request : %s", notificationRequest)); + restTemplate.postForEntity(notificationUrl, req, Object.class); + } catch (Exception e) { + Logger.error(String.format(EXCEPTION, e.getMessage())); + } + }).start(); + } + } \ No newline at end of file diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java index 0b7e4357c..e9a15cd7c 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java @@ -9,7 +9,6 @@ * @author karthik * */ -@Service public interface UserRegistrationNotificationService { public void sendNotification(UserRegistration userRegistration); diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java index bbcccaede..d5b8b4414 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java @@ -1,17 +1,20 @@ package org.sunbird.user.registration.service; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; import org.sunbird.common.util.NotificationUtil; -import org.sunbird.common.util.PropertiesCache; import org.sunbird.user.registration.model.UserRegistration; +import org.sunbird.user.registration.util.UserRegistrationStatus; +@Service public class UserRegistrationNotificationServiceImpl implements UserRegistrationNotificationService { @Autowired @@ -43,10 +46,7 @@ public void sendNotification(UserRegistration userRegistration) { notificationMessage(userRegistration.getStatus(), userRegistration.getRegistrationCode())); if (notificationObj.get(Constants.TEMPLATE) != null) { - notificationUtil.sendNotification(sendTo, notificationObj, - PropertiesCache.getInstance().getProperty(Constants.SENDER_MAIL), - PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_HOST) - + PropertiesCache.getInstance().getProperty(Constants.NOTIFICATION_ENDPOINT)); + notificationUtil.sendNotification(Arrays.asList(notificationObj)); } } @@ -54,23 +54,38 @@ private Map notificationMessage(String status, String regCode) { Map template = new HashMap<>(); template.put(Constants.ID, Constants.USER_REGISTERATION_TEMPLATE); Map params = new HashMap<>(); - params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", status)); - params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", status)); + template.put("params", params); switch (status) { case "WF_INITIATED": params.put(Constants.TITLE, serverProperties.getUserRegistrationThankyouMessage()); + params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", + UserRegistrationStatus.WF_INITIATED.getName())); + params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", + UserRegistrationStatus.WF_INITIATED.getName())); params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationInitiatedMessage() .replace("{regCode}", "" + regCode + "")); break; case "WF_APPROVED": + params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", + UserRegistrationStatus.WF_APPROVED.getName())); + params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", + UserRegistrationStatus.WF_APPROVED.getName())); params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationApprovedMessage()); params.put("btn-url", serverProperties.getUserRegistrationDomainName()); params.put("btn-name", serverProperties.getUserRegisterationButtonName()); break; case "WF_DENIED": + params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", + UserRegistrationStatus.WF_DENIED.getName())); + params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", + UserRegistrationStatus.WF_DENIED.getName())); break; case "FAILED": + params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", + UserRegistrationStatus.FAILED.getName())); + params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", + UserRegistrationStatus.FAILED.getName())); params.put(Constants.STATUS, serverProperties.getUserRegistrationFailedMessage()); break; diff --git a/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java b/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java index 70c0beb54..d84e78ee9 100644 --- a/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java +++ b/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java @@ -8,15 +8,22 @@ */ public enum UserRegistrationStatus { - CREATED(1), WF_INITIATED(2), WF_APPROVED(3), WF_DENIED(4), FAILED(5); + CREATED(1, "Created"), WF_INITIATED(2, "Initiated"), WF_APPROVED(3, "Approved"), WF_DENIED(4, "Denied"), FAILED(5, + "Failed"); private int status = 0; + private String name; - UserRegistrationStatus(int status) { + UserRegistrationStatus(int status, String name) { this.status = status; + this.name = name; } public int getStatus() { return status; } + + public String getName() { + return name; + } } From 64eb94556d71c3fc37de49995e867fd28d2c0e8e Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Thu, 2 Jun 2022 13:36:02 +0530 Subject: [PATCH 16/22] Fix for run time error --- .../service/UserRegistrationNotificationService.java | 2 -- .../service/UserRegistrationNotificationServiceImpl.java | 2 ++ src/main/resources/application.properties | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java index 0b7e4357c..70df3e637 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java @@ -1,6 +1,5 @@ package org.sunbird.user.registration.service; -import org.springframework.stereotype.Service; import org.sunbird.user.registration.model.UserRegistration; /** @@ -9,7 +8,6 @@ * @author karthik * */ -@Service public interface UserRegistrationNotificationService { public void sendNotification(UserRegistration userRegistration); diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java index bbcccaede..3c0c50cfe 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java @@ -6,12 +6,14 @@ import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; import org.sunbird.common.util.NotificationUtil; import org.sunbird.common.util.PropertiesCache; import org.sunbird.user.registration.model.UserRegistration; +@Service public class UserRegistrationNotificationServiceImpl implements UserRegistrationNotificationService { @Autowired diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index e8468bfe4..ccaf87de1 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -185,7 +185,7 @@ kafka.topics.user.registration.createUser=workflow.user.registration.createUser user.registration.dept.exclude.list=0133334975707217922 user.registration.workflow.service.name=user_registration #Registration email template message -user.registration.subject=iGOT-Registeration +user.registration.subject=iGOT-Registration user.registration.title=iGOT registration {status} user.registration.status=Your registration request is {status}. user.registration.thankyou.message=Thankyou for registering in iGOT! From 02972a17d54b9609f40b4cde865c04cac4f6be32 Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Fri, 3 Jun 2022 12:15:45 +0530 Subject: [PATCH 17/22] Added functionality for user creation --- .../common/util/CbExtServerProperties.java | 64 ++++++ .../org/sunbird/common/util/Constants.java | 26 ++- .../registration/model/UserRegistration.java | 23 +++ .../service/UserRegistrationServiceImpl.java | 27 ++- .../user/service/UserUtilityService.java | 2 +- .../user/service/UserUtilityServiceImpl.java | 187 +++++++++++++++--- src/main/resources/application.properties | 11 +- 7 files changed, 304 insertions(+), 36 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index f01666b5e..3385aeb69 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -33,6 +33,9 @@ public class CbExtServerProperties { @Value("${sb.service.url}") private String sbUrl; + @Value("${sb.service.user.create.path}") + private String lmsUserCreatePath; + @Value("${sunbird.user.search.endpoint}") private String userSearchEndPoint; @@ -279,7 +282,20 @@ public class CbExtServerProperties { @Value("${user.registration.preApproved.domain}") private String userRegistrationPreApprovedDomainList; + @Value("${sb.discussion.hub.host}") + private String discussionHubHost; + + @Value("${sb.node.bb.user.create.path}") + private String discussionHubCreateUserPath; + + @Value("${sb.service.reset.password.path}") + private String sbResetPasswordPath; + + @Value("${sb.service.send.notify.email.path}") + private String sbSendNotificationEmailPath; + @Value("${sb.service.assign.role.path}") + private String sbAssignRolePath; public String getUserAssessmentSubmissionDuration() { return userAssessmentSubmissionDuration; @@ -369,6 +385,14 @@ public void setSbUrl(String sbUrl) { this.sbUrl = sbUrl; } + public String getLmsUserCreatePath() { + return lmsUserCreatePath; + } + + public void setLmsUserCreatePath(String lmsUserCreatePath) { + this.lmsUserCreatePath = lmsUserCreatePath; + } + public String getSbHubGraphServiceUrl() { return sbHubGraphServiceUrl; } @@ -1019,4 +1043,44 @@ public List getUserRegistrationPreApprovedDomainList() { public void setUserRegistrationPreApprovedDomainList(String userRegistrationPreApprovedDomainList) { this.userRegistrationPreApprovedDomainList = userRegistrationPreApprovedDomainList; } + + public String getDiscussionHubHost() { + return discussionHubHost; + } + + public void setDiscussionHubHost(String discussionHubHost) { + this.discussionHubHost = discussionHubHost; + } + + public String getDiscussionHubCreateUserPath() { + return discussionHubCreateUserPath; + } + + public void setDiscussionHubCreateUserPath(String discussionHubCreateUserPath) { + this.discussionHubCreateUserPath = discussionHubCreateUserPath; + } + + public String getSbResetPasswordPath() { + return sbResetPasswordPath; + } + + public void setSbResetPasswordPath(String sbResetPasswordPath) { + this.sbResetPasswordPath = sbResetPasswordPath; + } + + public String getSbSendNotificationEmailPath() { + return sbSendNotificationEmailPath; + } + + public void setSbSendNotificationEmailPath(String sbSendNotificationEmailPath) { + this.sbSendNotificationEmailPath = sbSendNotificationEmailPath; + } + + public String getSbAssignRolePath() { + return sbAssignRolePath; + } + + public void setSbAssignRolePath(String sbAssignRolePath) { + this.sbAssignRolePath = sbAssignRolePath; + } } \ No newline at end of file diff --git a/src/main/java/org/sunbird/common/util/Constants.java b/src/main/java/org/sunbird/common/util/Constants.java index 856f9dd24..6b61a4333 100644 --- a/src/main/java/org/sunbird/common/util/Constants.java +++ b/src/main/java/org/sunbird/common/util/Constants.java @@ -12,6 +12,7 @@ public class Constants { public static final String LAST_NAME = "last_name"; public static final String MIDDLE_NAME = "middle_name"; public static final String FIRSTNAME = "firstName"; + public static final String SURNAME = "surname"; public static final String LASTNAME = "lastName"; public static final String CONTACT_PHONE_NUMBER_OFFICE = "contact_phone_number_office"; public static final String CONTACT_PHONE_NUMBER_HOME = "contact_phone_number_home"; @@ -230,6 +231,7 @@ public class Constants { public static final String VALUE = "value"; public static final String DEPT_NAME = "deptName"; public static final String PROFILE_DETAILS = "profileDetails"; + public static final String PROFESSIONAL_DETAILS = "professionalDetails"; public static final String CONTENT_TYPE = "Content-Type"; public static final String APPLICATION_JSON = "application/json"; public static final String OSID = "osid"; @@ -283,7 +285,6 @@ public class Constants { public static final String EID = "AUDIT"; public static final String PDATA_ID = "dev.sunbird.cb.ext.service"; public static final String PDATA_PID = "sunbird-cb-ext-service"; - public static final String TYPE = "WorkOrder"; public static final String CURRENT_STATE = "FirstLogin"; public static final String LOGIN_TIME = "login_time"; public static final List PROPS = Collections.unmodifiableList(Arrays.asList("WAT")); @@ -394,10 +395,31 @@ public class Constants { public static final String DESCRIPTION = "description"; public static final String TEMPLATE = "template"; public static final String USER_REGISTERATION_TEMPLATE = "user-registration"; - public static final String EMAIL_EXIST_ERROR = "Email id already registered"; + public static final String EMAIL_VERIFIED = "emailVerified"; + public static final String USER_NAME = "userName"; + public static final String USER_FULL_NAME = "fullName"; + + public static final String MANDATORY_FIELDS_EXISTS = "mandatoryFieldsExists"; + public static final String KEY = "key"; + public static final String TYPE = "type"; + public static final String LINK = "link"; + public static final String ALLOWED_LOGGING = "allowedLoging"; public static final String API_VERSION_1 = "1.0"; + public static final String BODY = "body"; + public static final String EMAIL_TEMPLATE_TYPE = "emailTemplateType"; + public static final String MODE = "mode"; + public static final String ORG_NAME = "orgName"; + public static final String RECIPIENT_EMAILS = "recipientEmails"; + public static final String SET_PASSWORD_LINK = "setPasswordLink"; + public static final String WELCOME_MESSAGE = "welcomeMessage"; + public static final String HELLO = "Hello"; + public static final String WELCOME_EMAIL_TEMPLATE_TYPE = "iGotWelcome"; + public static final String WELCOME_EMAIL_MESSAGE = "Welcome Email"; + public static final String ORGANIZATION_ID = "organisationId"; + public static final String ROLES = "roles"; + public static final String PUBLIC = "PUBLIC"; private Constants() { throw new IllegalStateException("Utility class"); diff --git a/src/main/java/org/sunbird/user/registration/model/UserRegistration.java b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java index 3c8ac9f19..d433f0a88 100644 --- a/src/main/java/org/sunbird/user/registration/model/UserRegistration.java +++ b/src/main/java/org/sunbird/user/registration/model/UserRegistration.java @@ -14,6 +14,8 @@ public class UserRegistration extends UserRegistrationInfo { private long updatedOn; private String createdBy; private String updatedBy; + private String userId; + private String userName; public String getWfId() { return wfId; @@ -71,4 +73,25 @@ public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String toMininumString() { + StringBuilder strBuilder = new StringBuilder("[ UserRegistrationCode : "); + strBuilder.append(this.getRegistrationCode()).append(", UserId : ").append(this.getUserId()).append("]"); + return strBuilder.toString(); + } } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index 8c41b583d..86a0c8319 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -136,15 +136,7 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { @Override public SBApiResponse getUserRegistrationDetails(String registrationCode) { SBApiResponse response = createDefaultResponse(Constants.USER_REGISTRATION_RETRIEVE_API); - UserRegistration userRegistration = null; - try { - Map esObject = indexerService.readEntity(serverProperties.getUserRegistrationIndex(), - serverProperties.getEsProfileIndexType(), registrationCode); - userRegistration = mapper.convertValue(esObject, UserRegistration.class); - } catch (Exception e) { - LOGGER.error(String.format("Exception in %s : %s", "getUserRegistrationDetails", e.getMessage())); - } - + UserRegistration userRegistration = getUserRegistrationForRegCode(registrationCode); if (userRegistration != null) { response.getResult().put(Constants.RESULT, userRegistration); } else { @@ -214,7 +206,11 @@ public void initiateCreateUserFlow(String registrationCode) { * 5. Assign Role 6. Reset Password and get activation link */ LOGGER.info("Initiated User Creation flow for Reg. Code :: " + registrationCode); - + if (userUtilityService.createUser(getUserRegistrationForRegCode(registrationCode))) { + LOGGER.info("Successfully completed user creation flow."); + } else { + // TODO - Need to handle error cases + } } catch (Exception e) { LOGGER.error("Failed to process user create flow.", e); } @@ -375,4 +371,15 @@ public Boolean emailValidation(String email) { private Boolean isPreApprovedDomain(String email) { return serverProperties.getUserRegistrationPreApprovedDomainList().contains(email.split("@")[1]); } + + private UserRegistration getUserRegistrationForRegCode(String registrationCode) { + try { + Map esObject = indexerService.readEntity(serverProperties.getUserRegistrationIndex(), + serverProperties.getEsProfileIndexType(), registrationCode); + return mapper.convertValue(esObject, UserRegistration.class); + } catch (Exception e) { + LOGGER.error(String.format("Exception in %s : %s", "getUserRegistrationDetails", e.getMessage())); + } + return null; + } } diff --git a/src/main/java/org/sunbird/user/service/UserUtilityService.java b/src/main/java/org/sunbird/user/service/UserUtilityService.java index 3db496faa..619c190bd 100644 --- a/src/main/java/org/sunbird/user/service/UserUtilityService.java +++ b/src/main/java/org/sunbird/user/service/UserUtilityService.java @@ -24,7 +24,7 @@ public interface UserUtilityService { boolean updateUser(UserRegistration userRegistration); - String getActivationLink(UserRegistration userRegistration); + boolean getActivationLink(UserRegistration userRegistration); boolean createNodeBBUser(UserRegistration userRegistration); } \ No newline at end of file diff --git a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java index 259ddff99..7f584f972 100644 --- a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java +++ b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java @@ -1,6 +1,8 @@ package org.sunbird.user.service; import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -13,6 +15,7 @@ import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; +import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.sunbird.cassandra.utils.CassandraOperation; import org.sunbird.common.model.SearchUserApiContent; @@ -56,7 +59,6 @@ public class UserUtilityServiceImpl implements UserUtilityService { CbExtServerProperties serverConfig; private CbExtLogger logger = new CbExtLogger(getClass().getName()); - private final String SEARCH_RESULT = "Search API response: "; public boolean validateUser(String userId) { return validateUser(StringUtils.EMPTY, userId); @@ -64,16 +66,13 @@ public boolean validateUser(String userId) { @Override public boolean validateUser(String rootOrg, String userId) { - Map requestMap = new HashMap<>(); - Map request = new HashMap<>(); - Map filters = new HashMap<>(); filters.put(Constants.USER_ID, userId); request.put(Constants.FILTERS, filters); - requestMap.put("request", request); + requestMap.put(Constants.REQUEST, request); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); try { @@ -81,7 +80,7 @@ public boolean validateUser(String rootOrg, String userId) { HttpEntity requestEnty = new HttpEntity<>(reqBodyData, headers); - String serverUrl = props.getSbUrl() + "private/user/v1/search"; + String serverUrl = props.getSbUrl() + props.getUserSearchEndPoint(); SunbirdApiResp sunbirdApiResp = restTemplate.postForObject(serverUrl, requestEnty, SunbirdApiResp.class); @@ -92,7 +91,6 @@ public boolean validateUser(String rootOrg, String userId) { } catch (Exception e) { throw new ApplicationLogicError("Sunbird Service ERROR: ", e); } - } @Override @@ -150,7 +148,6 @@ public Map getUsersDataFromUserIds(List userIds, List requestEnty = new HttpEntity<>(requestObj, headers); SearchUserApiResp searchUserResult = restTemplate.postForObject(url, requestEnty, SearchUserApiResp.class); - logger.debug(SEARCH_RESULT + searchUserResult.toString()); if (searchUserResult != null && Constants.OK.equalsIgnoreCase(searchUserResult.getResponseCode()) && searchUserResult.getResult().getResponse().getCount() > 0) { for (SearchUserApiContent searchUserApiContent : searchUserResult.getResult().getResponse() @@ -192,10 +189,14 @@ public Map updateLogin(LastLoginInfo userLoginInfo) { } @Override - public Map getUsersReadData(String userId, String authToken, String X_authToken) { + public Map getUsersReadData(String userId, String authToken, String userAuthToken) { Map header = new HashMap<>(); - header.put(Constants.AUTH_TOKEN, authToken); - header.put(Constants.X_AUTH_TOKEN, X_authToken); + if (StringUtils.isNotEmpty(authToken)) { + header.put(Constants.AUTH_TOKEN, authToken); + } + if (StringUtils.isNotEmpty(userAuthToken)) { + header.put(Constants.X_AUTH_TOKEN, userAuthToken); + } Map readData = (Map) outboundRequestHandlerService .fetchUsingGetWithHeadersProfile(serverConfig.getSbUrl() + serverConfig.getLmsUserReadPath() + userId, header); @@ -206,25 +207,167 @@ public Map getUsersReadData(String userId, String authToken, Str @Override public boolean createUser(UserRegistration userRegistration) { - // TODO Auto-generated method stub - return false; + boolean retValue = false; + Map request = new HashMap<>(); + Map requestBody = new HashMap(); + requestBody.put(Constants.EMAIL, userRegistration.getEmail()); + requestBody.put(Constants.CHANNEL, userRegistration.getDeptName()); + requestBody.put(Constants.FIRSTNAME, userRegistration.getFirstName()); + requestBody.put(Constants.LASTNAME, userRegistration.getLastName()); + requestBody.put(Constants.EMAIL_VERIFIED, true); + request.put(Constants.REQUEST, requestBody); + try { + Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + props.getSbUrl() + props.getLmsUserCreatePath(), request, getDefaultHeaders()); + if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { + Map result = (Map) readData.get(Constants.RESULT); + userRegistration.setUserId((String) result.get(Constants.USER_ID)); + Map userData = getUsersReadData(userRegistration.getUserId(), StringUtils.EMPTY, + StringUtils.EMPTY); + if (!CollectionUtils.isEmpty(userData)) { + userRegistration.setUserName((String) userData.get(Constants.USER_NAME)); + retValue = createNodeBBUser(userRegistration); + } + } + } catch (RestClientException e) { + logger.info(e.getMessage()); + } + printMethodExecutionResult("Create User", userRegistration.toMininumString(), retValue); + return retValue; } @Override - public boolean updateUser(UserRegistration userRegistration) { - // TODO Auto-generated method stub - return false; + public boolean createNodeBBUser(UserRegistration userRegistration) { + boolean retValue = false; + Map request = new HashMap<>(); + Map requestBody = new HashMap(); + requestBody.put(Constants.USER_NAME.toLowerCase(), userRegistration.getUserName()); + requestBody.put(Constants.IDENTIFIER, userRegistration.getUserId()); + requestBody.put(Constants.USER_FULL_NAME.toLowerCase(), + userRegistration.getFirstName() + " " + userRegistration.getLastName()); + request.put(Constants.REQUEST, requestBody); + + Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + props.getDiscussionHubHost() + props.getDiscussionHubCreateUserPath(), request, getDefaultHeaders()); + if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { + retValue = updateUser(userRegistration); + } + printMethodExecutionResult("Create NodeBB User", userRegistration.toMininumString(), retValue); + return retValue; } @Override - public String getActivationLink(UserRegistration userRegistration) { - // TODO Auto-generated method stub - return null; + public boolean updateUser(UserRegistration userRegistration) { + boolean retValue = false; + Map request = new HashMap<>(); + Map requestBody = new HashMap(); + requestBody.put(Constants.USER_ID, userRegistration.getUserId()); + Map profileDetails = new HashMap(); + profileDetails.put(Constants.MANDATORY_FIELDS_EXISTS, false); + Map employementDetails = new HashMap(); + employementDetails.put(Constants.DEPARTMENTNAME, userRegistration.getDeptName()); + profileDetails.put(Constants.EMPLOYMENTDETAILS, employementDetails); + Map personalDetails = new HashMap(); + personalDetails.put(Constants.FIRSTNAME.toLowerCase(), userRegistration.getFirstName()); + personalDetails.put(Constants.SURNAME, userRegistration.getLastName()); + personalDetails.put(Constants.PRIMARY_EMAIL, userRegistration.getEmail()); + profileDetails.put(Constants.PERSONAL_DETAILS, personalDetails); + + if (StringUtils.isNotEmpty(userRegistration.getPosition())) { + Map professionDetailObj = new HashMap(); + professionDetailObj.put(Constants.DESIGNATION, userRegistration.getPosition()); + List> professionalDetailsList = new ArrayList>(); + professionalDetailsList.add(professionDetailObj); + profileDetails.put(Constants.PROFESSIONAL_DETAILS, professionalDetailsList); + } + requestBody.put(Constants.PROFILE_DETAILS, profileDetails); + request.put(Constants.REQUEST, requestBody); + Map readData = (Map) outboundRequestHandlerService + .fetchResultUsingPost(props.getSbUrl() + props.getLmsUserUpdatePath(), request, getDefaultHeaders()); + if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { + retValue = getActivationLink(userRegistration); + } + printMethodExecutionResult("UpdateUser", userRegistration.toMininumString(), retValue); + return retValue; } @Override - public boolean createNodeBBUser(UserRegistration userRegistration) { - // TODO Auto-generated method stub - return false; + public boolean getActivationLink(UserRegistration userRegistration) { + boolean retValue = false; + Map request = new HashMap(); + request.put(Constants.USER_ID, userRegistration.getUserId()); + request.put(Constants.KEY, Constants.EMAIL); + request.put(Constants.TYPE, Constants.EMAIL); + Map readData = (Map) outboundRequestHandlerService + .fetchResultUsingPost(props.getSbUrl() + props.getSbResetPasswordPath(), request, getDefaultHeaders()); + if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { + Map result = (Map) readData.get(Constants.RESULT); + if (!CollectionUtils.isEmpty(result)) { + retValue = sendWelcomeEmail((String) result.get(Constants.LINK), userRegistration); + } + } + printMethodExecutionResult("GetActivationLink", userRegistration.toMininumString(), retValue); + return retValue; + } + + public boolean sendWelcomeEmail(String activationLink, UserRegistration userRegistration) { + boolean retValue = false; + Map request = new HashMap<>(); + Map requestBody = new HashMap(); + requestBody.put(Constants.ALLOWED_LOGGING, "You can use your email to Login"); + requestBody.put(Constants.BODY, Constants.HELLO); + requestBody.put(Constants.EMAIL_TEMPLATE_TYPE, Constants.WELCOME_EMAIL_TEMPLATE_TYPE); + requestBody.put(Constants.FIRSTNAME, userRegistration.getFirstName()); + requestBody.put(Constants.LINK, activationLink); + requestBody.put(Constants.MODE, Constants.EMAIL); + requestBody.put(Constants.ORG_NAME, userRegistration.getDeptName()); + requestBody.put(Constants.RECIPIENT_EMAILS, Arrays.asList(userRegistration.getEmail())); + requestBody.put(Constants.SET_PASSWORD_LINK, true); + requestBody.put(Constants.SUBJECT, Constants.WELCOME_EMAIL_MESSAGE); + requestBody.put(Constants.WELCOME_MESSAGE, Constants.HELLO); + + request.put(Constants.REQUEST, requestBody); + + Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + props.getSbUrl() + props.getSbSendNotificationEmailPath(), request, getDefaultHeaders()); + if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { + retValue = assignRole(userRegistration); + } + printMethodExecutionResult("SendWelcomeEmail", userRegistration.toMininumString(), retValue); + return retValue; + } + + public boolean assignRole(UserRegistration userRegistration) { + boolean retValue = false; + Map request = new HashMap<>(); + Map requestBody = new HashMap(); + requestBody.put(Constants.ORGANIZATION_ID, userRegistration.getDeptId()); + requestBody.put(Constants.USER_ID, userRegistration.getUserId()); + requestBody.put(Constants.ROLES, Arrays.asList(Constants.PUBLIC)); + request.put(Constants.REQUEST, requestBody); + Map readData = (Map) outboundRequestHandlerService + .fetchResultUsingPost(props.getSbUrl() + props.getSbAssignRolePath(), request, getDefaultHeaders()); + if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { + retValue = true; + } + printMethodExecutionResult("AssignRole", userRegistration.toMininumString(), retValue); + return retValue; + } + + private void printMethodExecutionResult(String methodAction, String objectDetails, boolean isSuccess) { + StringBuilder strBuilder = new StringBuilder("Action : [").append(methodAction).append("] "); + if (isSuccess) { + strBuilder.append(" is successfully executed. "); + } else { + strBuilder.append(" is failed to execute. "); + } + strBuilder.append("For UserRegistration : ").append(objectDetails); + logger.info(strBuilder.toString()); + } + + private Map getDefaultHeaders() { + Map headers = new HashMap(); + headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); + return headers; } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ccaf87de1..1aa60a424 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -14,8 +14,12 @@ wf.service.transitionPath=v1/workflow/transition user.enable.multidept.mapping=false #learner.service.url=learner-service:9000 -sb.service.url= http://learner-service:9000/ +sb.service.url=http://learner-service:9000/ sb.org.search.path=v1/org/search +sb.service.user.create.path=v3/user/create +sb.service.reset.password.path=private/user/v1/password/reset +sb.service.send.notify.email.path=private/user/v1/notification/email +sb.service.assign.role.path=private/user/v1/assign/role sb.hub.graph.service.url=http://hub-graph-service:4013 @@ -194,3 +198,8 @@ user.registration.approved.message=Click on the below link to set your password user.registration.failed.message=Please try again later. user.registeration.route.button.name=Click here user.registration.domain.name=https://igot-dev.in/ + +#Discussion hub node details +sb.discussion.hub.host=http://discussionsmw-service:3002/ +sb.node.bb.user.create.path=discussion/user/v1/create + From 8dd923546ce78be9f2ff5340cd2b44bfd3a45aa7 Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Fri, 3 Jun 2022 14:37:19 +0530 Subject: [PATCH 18/22] Fixed pre approved domain processing --- .../sunbird/common/util/CbExtServerProperties.java | 12 ++++++------ .../service/UserRegistrationConsumer.java | 14 ++++++++++++++ .../service/UserRegistrationServiceImpl.java | 5 +++-- src/main/resources/application.properties | 1 + 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index 3385aeb69..74a6767e1 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -240,8 +240,8 @@ public class CbExtServerProperties { @Value("${kafka.topics.user.registration.register.event}") private String userRegistrationTopic; - @Value("${kafka.topics.user.registration.createUser}") - private String userRegistrationCreateUserTopic; + @Value("${kafka.topics.user.registration.auto.createUser}") + private String userRegistrationAutoCreateUserTopic; @Value("${user.registration.domain}") private String userRegistrationDomain; @@ -932,12 +932,12 @@ public void setUserRegistrationTopic(String userRegistrationTopic) { this.userRegistrationTopic = userRegistrationTopic; } - public String getUserRegistrationCreateUserTopic() { - return userRegistrationCreateUserTopic; + public String getUserRegistrationAutoCreateUserTopic() { + return userRegistrationAutoCreateUserTopic; } - public void setUserRegistrationCreateUserTopic(String userRegistrationCreateUserTopic) { - this.userRegistrationCreateUserTopic = userRegistrationCreateUserTopic; + public void setUserRegistrationAutoCreateUserTopic(String userRegistrationAutoCreateUserTopic) { + this.userRegistrationAutoCreateUserTopic = userRegistrationAutoCreateUserTopic; } public List getUserRegistrationDomain() { diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index ff7dd593e..7b4137716 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -112,6 +112,20 @@ public void processCreateUserMessage(ConsumerRecord data) { } } + @KafkaListener(topicPartitions = { + @TopicPartition(topic = "${kafka.topics.user.registration.auto.createUser}", partitions = { "0", "1", "2", + "3" }) }) + public void processAutoCreateUserEvent(ConsumerRecord data) { + try { + UserRegistration userRegistration = gson.fromJson(data.value(), UserRegistration.class); + LOGGER.info("Consumed Request in Topic to auto create user in registration:: " + + mapper.writeValueAsString(userRegistration)); + userRegService.initiateCreateUserFlow(userRegistration.getRegistrationCode()); + } catch (Exception e) { + LOGGER.error("Failed to process message in Topic to auto create user in registration.", e); + } + } + private WfRequest wfRequestObj(UserRegistration userRegistration) { WfRequest wfRequest = new WfRequest(); wfRequest.setState(Constants.INITIATE); diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index 86a0c8319..ac171b423 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -104,7 +104,8 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { if (status.equals(RestStatus.CREATED) || status.equals(RestStatus.OK)) { if (isPreApprovedDomain(regDocument.getEmail())) { // Fire createUser event - kafkaProducer.push(serverProperties.getUserRegistrationCreateUserTopic(), regDocument); + kafkaProducer.push(serverProperties.getUserRegistrationAutoCreateUserTopic(), + regDocument); } else { // Fire register event kafkaProducer.push(serverProperties.getUserRegistrationTopic(), regDocument); @@ -209,7 +210,7 @@ public void initiateCreateUserFlow(String registrationCode) { if (userUtilityService.createUser(getUserRegistrationForRegCode(registrationCode))) { LOGGER.info("Successfully completed user creation flow."); } else { - // TODO - Need to handle error cases + LOGGER.error("Failed to create user for Reg.Code :: " + registrationCode); } } catch (Exception e) { LOGGER.error("Failed to process user create flow.", e); diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 1aa60a424..8a88551ea 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -185,6 +185,7 @@ user.registration.domain=gmail.com es.user.registration.index=user_registration kafka.topics.user.registration.register.event=user.register.event kafka.topics.user.registration.createUser=workflow.user.registration.createUser +kafka.topics.user.registration.auto.createUser=user.register.createUser.event #Provide Dept Id as comma separated values here to exclude the details user.registration.dept.exclude.list=0133334975707217922 user.registration.workflow.service.name=user_registration From 86152bee386cfcd0f2c8c9faac3d4364987a54b4 Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Fri, 3 Jun 2022 15:53:24 +0530 Subject: [PATCH 19/22] Updated the path properly --- src/main/resources/application.properties | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8a88551ea..5409a0670 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -14,12 +14,12 @@ wf.service.transitionPath=v1/workflow/transition user.enable.multidept.mapping=false #learner.service.url=learner-service:9000 -sb.service.url=http://learner-service:9000/ -sb.org.search.path=v1/org/search -sb.service.user.create.path=v3/user/create -sb.service.reset.password.path=private/user/v1/password/reset -sb.service.send.notify.email.path=private/user/v1/notification/email -sb.service.assign.role.path=private/user/v1/assign/role +sb.service.url=http://learner-service:9000 +sb.org.search.path=/v1/org/search +sb.service.user.create.path=/v3/user/create +sb.service.reset.password.path=/private/user/v1/password/reset +sb.service.send.notify.email.path=/private/user/v1/notification/email +sb.service.assign.role.path=/private/user/v1/assign/role sb.hub.graph.service.url=http://hub-graph-service:4013 @@ -32,8 +32,8 @@ spring.data.cassandra.sb.password=cassandra sunbird.course.service.host=http://lms-service:9000/ lms.system.settings.path=v1/system/settings/get/PatchConfig -lms.user.read.path=private/user/v1/read/ -lms.user.update.path=private/user/v1/update +lms.user.read.path=/private/user/v1/read/ +lms.user.update.path=/private/user/v1/update progress.api.endpoint=v1/content/state/read participants.api.endpoint=v1/batch/participants/list sb.api.key=apiKey From 5b8f5cbf4107ab8bd95fcb77b2141132d183ab2c Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Fri, 3 Jun 2022 17:27:35 +0530 Subject: [PATCH 20/22] Fix for user update API. --- .../java/org/sunbird/user/service/UserUtilityServiceImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java index 7f584f972..46a7e00f7 100644 --- a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java +++ b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java @@ -283,7 +283,7 @@ public boolean updateUser(UserRegistration userRegistration) { requestBody.put(Constants.PROFILE_DETAILS, profileDetails); request.put(Constants.REQUEST, requestBody); Map readData = (Map) outboundRequestHandlerService - .fetchResultUsingPost(props.getSbUrl() + props.getLmsUserUpdatePath(), request, getDefaultHeaders()); + .fetchResultUsingPatch(props.getSbUrl() + props.getLmsUserUpdatePath(), request, getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { retValue = getActivationLink(userRegistration); } From ef2480e02d7599f34511ee61378917b8cf8eddeb Mon Sep 17 00:00:00 2001 From: karthik-tarento Date: Fri, 3 Jun 2022 18:28:10 +0530 Subject: [PATCH 21/22] Fixed reset password API issue and re-ordered create user flow. --- .../service/UserRegistrationServiceImpl.java | 2 +- .../user/service/UserUtilityServiceImpl.java | 99 ++++++++++--------- 2 files changed, 52 insertions(+), 49 deletions(-) diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index ac171b423..736f4527a 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -121,7 +121,7 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { } } } catch (Exception e) { - LOGGER.error(String.format("Exception in %s : %s", "registerUser", e.getMessage())); + LOGGER.error(String.format("Exception in %s : %s", "registerUser", e.getMessage()), e); errMsg = "Failed to process message. Exception: " + e.getMessage(); } } diff --git a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java index 46a7e00f7..70d1484f1 100644 --- a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java +++ b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java @@ -9,13 +9,14 @@ import java.util.Map; import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; -import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.sunbird.cassandra.utils.CassandraOperation; import org.sunbird.common.model.SearchUserApiContent; @@ -26,7 +27,6 @@ import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; import org.sunbird.core.exception.ApplicationLogicError; -import org.sunbird.core.logger.CbExtLogger; import org.sunbird.telemetry.model.LastLoginInfo; import org.sunbird.user.registration.model.UserRegistration; import org.sunbird.user.util.TelemetryUtils; @@ -58,7 +58,7 @@ public class UserUtilityServiceImpl implements UserUtilityService { @Autowired CbExtServerProperties serverConfig; - private CbExtLogger logger = new CbExtLogger(getClass().getName()); + private Logger logger = LoggerFactory.getLogger(UserUtilityServiceImpl.class); public boolean validateUser(String userId) { return validateUser(StringUtils.EMPTY, userId); @@ -226,36 +226,17 @@ public boolean createUser(UserRegistration userRegistration) { StringUtils.EMPTY); if (!CollectionUtils.isEmpty(userData)) { userRegistration.setUserName((String) userData.get(Constants.USER_NAME)); - retValue = createNodeBBUser(userRegistration); + retValue = updateUser(userRegistration); } } - } catch (RestClientException e) { - logger.info(e.getMessage()); + } catch (Exception e) { + logger.error("Failed to run the create user flow. UserRegCode : " + userRegistration.getRegistrationCode(), + e); } printMethodExecutionResult("Create User", userRegistration.toMininumString(), retValue); return retValue; } - @Override - public boolean createNodeBBUser(UserRegistration userRegistration) { - boolean retValue = false; - Map request = new HashMap<>(); - Map requestBody = new HashMap(); - requestBody.put(Constants.USER_NAME.toLowerCase(), userRegistration.getUserName()); - requestBody.put(Constants.IDENTIFIER, userRegistration.getUserId()); - requestBody.put(Constants.USER_FULL_NAME.toLowerCase(), - userRegistration.getFirstName() + " " + userRegistration.getLastName()); - request.put(Constants.REQUEST, requestBody); - - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( - props.getDiscussionHubHost() + props.getDiscussionHubCreateUserPath(), request, getDefaultHeaders()); - if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { - retValue = updateUser(userRegistration); - } - printMethodExecutionResult("Create NodeBB User", userRegistration.toMininumString(), retValue); - return retValue; - } - @Override public boolean updateUser(UserRegistration userRegistration) { boolean retValue = false; @@ -285,19 +266,58 @@ public boolean updateUser(UserRegistration userRegistration) { Map readData = (Map) outboundRequestHandlerService .fetchResultUsingPatch(props.getSbUrl() + props.getLmsUserUpdatePath(), request, getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { - retValue = getActivationLink(userRegistration); + retValue = assignRole(userRegistration); } printMethodExecutionResult("UpdateUser", userRegistration.toMininumString(), retValue); return retValue; } + public boolean assignRole(UserRegistration userRegistration) { + boolean retValue = false; + Map request = new HashMap<>(); + Map requestBody = new HashMap(); + requestBody.put(Constants.ORGANIZATION_ID, userRegistration.getDeptId()); + requestBody.put(Constants.USER_ID, userRegistration.getUserId()); + requestBody.put(Constants.ROLES, Arrays.asList(Constants.PUBLIC)); + request.put(Constants.REQUEST, requestBody); + Map readData = (Map) outboundRequestHandlerService + .fetchResultUsingPost(props.getSbUrl() + props.getSbAssignRolePath(), request, getDefaultHeaders()); + if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { + retValue = createNodeBBUser(userRegistration); + } + printMethodExecutionResult("AssignRole", userRegistration.toMininumString(), retValue); + return retValue; + } + + @Override + public boolean createNodeBBUser(UserRegistration userRegistration) { + boolean retValue = false; + Map request = new HashMap<>(); + Map requestBody = new HashMap(); + requestBody.put(Constants.USER_NAME.toLowerCase(), userRegistration.getUserName()); + requestBody.put(Constants.IDENTIFIER, userRegistration.getUserId()); + requestBody.put(Constants.USER_FULL_NAME.toLowerCase(), + userRegistration.getFirstName() + " " + userRegistration.getLastName()); + request.put(Constants.REQUEST, requestBody); + + Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + props.getDiscussionHubHost() + props.getDiscussionHubCreateUserPath(), request, getDefaultHeaders()); + if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { + retValue = getActivationLink(userRegistration); + } + printMethodExecutionResult("Create NodeBB User", userRegistration.toMininumString(), retValue); + return retValue; + } + @Override public boolean getActivationLink(UserRegistration userRegistration) { boolean retValue = false; Map request = new HashMap(); - request.put(Constants.USER_ID, userRegistration.getUserId()); - request.put(Constants.KEY, Constants.EMAIL); - request.put(Constants.TYPE, Constants.EMAIL); + Map requestBody = new HashMap(); + requestBody.put(Constants.USER_ID, userRegistration.getUserId()); + requestBody.put(Constants.KEY, Constants.EMAIL); + requestBody.put(Constants.TYPE, Constants.EMAIL); + request.put(Constants.REQUEST, requestBody); Map readData = (Map) outboundRequestHandlerService .fetchResultUsingPost(props.getSbUrl() + props.getSbResetPasswordPath(), request, getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { @@ -330,27 +350,10 @@ public boolean sendWelcomeEmail(String activationLink, UserRegistration userRegi Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( props.getSbUrl() + props.getSbSendNotificationEmailPath(), request, getDefaultHeaders()); - if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { - retValue = assignRole(userRegistration); - } - printMethodExecutionResult("SendWelcomeEmail", userRegistration.toMininumString(), retValue); - return retValue; - } - - public boolean assignRole(UserRegistration userRegistration) { - boolean retValue = false; - Map request = new HashMap<>(); - Map requestBody = new HashMap(); - requestBody.put(Constants.ORGANIZATION_ID, userRegistration.getDeptId()); - requestBody.put(Constants.USER_ID, userRegistration.getUserId()); - requestBody.put(Constants.ROLES, Arrays.asList(Constants.PUBLIC)); - request.put(Constants.REQUEST, requestBody); - Map readData = (Map) outboundRequestHandlerService - .fetchResultUsingPost(props.getSbUrl() + props.getSbAssignRolePath(), request, getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { retValue = true; } - printMethodExecutionResult("AssignRole", userRegistration.toMininumString(), retValue); + printMethodExecutionResult("SendWelcomeEmail", userRegistration.toMininumString(), retValue); return retValue; } From aa9fb7fd429db86372a87941543a067bbe44b403 Mon Sep 17 00:00:00 2001 From: nivetha Date: Mon, 6 Jun 2022 11:43:55 +0530 Subject: [PATCH 22/22] Notification service review changes --- .../org/sunbird/common/util/Constants.java | 15 +++++ .../UserRegistrationNotificationService.java | 1 - ...erRegistrationNotificationServiceImpl.java | 55 +++++++++---------- .../util/UserRegistrationStatus.java | 10 +--- 4 files changed, 44 insertions(+), 37 deletions(-) diff --git a/src/main/java/org/sunbird/common/util/Constants.java b/src/main/java/org/sunbird/common/util/Constants.java index 856f9dd24..3961209a7 100644 --- a/src/main/java/org/sunbird/common/util/Constants.java +++ b/src/main/java/org/sunbird/common/util/Constants.java @@ -394,6 +394,21 @@ public class Constants { public static final String DESCRIPTION = "description"; public static final String TEMPLATE = "template"; public static final String USER_REGISTERATION_TEMPLATE = "user-registration"; + public static final String STATUS_PARAM = "{status}"; + public static final String REG_CODE_PARAM = "{regCode}"; + public static final String BUTTON_URL = "btn-url"; + public static final String BUTTON_NAME = "btn-name"; + + // notification reuest params + public static final String MODE = "mode"; + public static final String DELIVERY_TYPE = "deliveryType"; + public static final String CONFIG = "config"; + public static final String IDS = "ids"; + + // wf status + public static final String INITIATED = "initiated"; + public static final String APPROVED = "approved"; + public static final String DENIED = "denied"; public static final String EMAIL_EXIST_ERROR = "Email id already registered"; diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java index e9a15cd7c..70df3e637 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationService.java @@ -1,6 +1,5 @@ package org.sunbird.user.registration.service; -import org.springframework.stereotype.Service; import org.sunbird.user.registration.model.UserRegistration; /** diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java index d5b8b4414..551528bd9 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java @@ -12,17 +12,16 @@ import org.sunbird.common.util.Constants; import org.sunbird.common.util.NotificationUtil; import org.sunbird.user.registration.model.UserRegistration; -import org.sunbird.user.registration.util.UserRegistrationStatus; @Service public class UserRegistrationNotificationServiceImpl implements UserRegistrationNotificationService { @Autowired CbExtServerProperties serverProperties; - + @Autowired NotificationUtil notificationUtil; - + @Override public void sendNotification(UserRegistration userRegistration) { List sendTo = new ArrayList() { @@ -34,14 +33,14 @@ public void sendNotification(UserRegistration userRegistration) { }; Map notificationObj = new HashMap<>(); - notificationObj.put("mode", Constants.EMAIL); - notificationObj.put("deliveryType", Constants.MESSAGE); - notificationObj.put("config", new HashMap() { + notificationObj.put(Constants.MODE, Constants.EMAIL); + notificationObj.put(Constants.DELIVERY_TYPE, Constants.MESSAGE); + notificationObj.put(Constants.CONFIG, new HashMap() { { put(Constants.SUBJECT, serverProperties.getUserRegistrationSubject()); } }); - notificationObj.put("ids", sendTo); + notificationObj.put(Constants.IDS, sendTo); notificationObj.put(Constants.TEMPLATE, notificationMessage(userRegistration.getStatus(), userRegistration.getRegistrationCode())); @@ -49,43 +48,43 @@ public void sendNotification(UserRegistration userRegistration) { notificationUtil.sendNotification(Arrays.asList(notificationObj)); } } - + private Map notificationMessage(String status, String regCode) { Map template = new HashMap<>(); template.put(Constants.ID, Constants.USER_REGISTERATION_TEMPLATE); Map params = new HashMap<>(); - template.put("params", params); + template.put(Constants.PARAMS, params); switch (status) { case "WF_INITIATED": params.put(Constants.TITLE, serverProperties.getUserRegistrationThankyouMessage()); - params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", - UserRegistrationStatus.WF_INITIATED.getName())); - params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", - UserRegistrationStatus.WF_INITIATED.getName())); + params.put(Constants.STATUS, + serverProperties.getUserRegistrationStatus().replace(Constants.STATUS_PARAM, "initiated")); + params.put(Constants.TITLE, + serverProperties.getUserRegistrationTitle().replace(Constants.STATUS_PARAM, "initiated")); params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationInitiatedMessage() - .replace("{regCode}", "" + regCode + "")); + .replace(Constants.REG_CODE_PARAM, "" + regCode + "")); break; case "WF_APPROVED": - params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", - UserRegistrationStatus.WF_APPROVED.getName())); - params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", - UserRegistrationStatus.WF_APPROVED.getName())); + params.put(Constants.STATUS, + serverProperties.getUserRegistrationStatus().replace(Constants.STATUS_PARAM, "approved")); + params.put(Constants.TITLE, + serverProperties.getUserRegistrationTitle().replace(Constants.STATUS_PARAM, "approved")); params.put(Constants.DESCRIPTION, serverProperties.getUserRegistrationApprovedMessage()); - params.put("btn-url", serverProperties.getUserRegistrationDomainName()); - params.put("btn-name", serverProperties.getUserRegisterationButtonName()); + params.put(Constants.BUTTON_URL, serverProperties.getUserRegistrationDomainName()); + params.put(Constants.BUTTON_NAME, serverProperties.getUserRegisterationButtonName()); break; case "WF_DENIED": - params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", - UserRegistrationStatus.WF_DENIED.getName())); - params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", - UserRegistrationStatus.WF_DENIED.getName())); + params.put(Constants.STATUS, + serverProperties.getUserRegistrationStatus().replace(Constants.STATUS_PARAM, "denied")); + params.put(Constants.TITLE, + serverProperties.getUserRegistrationTitle().replace(Constants.STATUS_PARAM, "denied")); break; case "FAILED": - params.put(Constants.STATUS, serverProperties.getUserRegistrationStatus().replace("{status}", - UserRegistrationStatus.FAILED.getName())); - params.put(Constants.TITLE, serverProperties.getUserRegistrationTitle().replace("{status}", - UserRegistrationStatus.FAILED.getName())); + params.put(Constants.STATUS, + serverProperties.getUserRegistrationStatus().replace(Constants.STATUS_PARAM, "failed")); + params.put(Constants.TITLE, + serverProperties.getUserRegistrationTitle().replace(Constants.STATUS_PARAM, "failed")); params.put(Constants.STATUS, serverProperties.getUserRegistrationFailedMessage()); break; diff --git a/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java b/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java index d84e78ee9..391e45990 100644 --- a/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java +++ b/src/main/java/org/sunbird/user/registration/util/UserRegistrationStatus.java @@ -8,22 +8,16 @@ */ public enum UserRegistrationStatus { - CREATED(1, "Created"), WF_INITIATED(2, "Initiated"), WF_APPROVED(3, "Approved"), WF_DENIED(4, "Denied"), FAILED(5, - "Failed"); + CREATED(1), WF_INITIATED(2), WF_APPROVED(3), WF_DENIED(4), FAILED(5); private int status = 0; - private String name; - UserRegistrationStatus(int status, String name) { + UserRegistrationStatus(int status) { this.status = status; - this.name = name; } public int getStatus() { return status; } - public String getName() { - return name; - } }