def lockUser(self, user_name):
        if StringHelper.isEmpty(user_name):
            return None

        userService = CdiUtil.bean(UserService)
        cacheService= CdiUtil.bean(CacheService)
        facesMessages = CdiUtil.bean(FacesMessages)
        facesMessages.setKeepMessages()

        find_user_by_uid = userService.getUser(user_name)
        if (find_user_by_uid == None):
            return None

        status_attribute_value = userService.getCustomAttribute(find_user_by_uid, .jans.tatus")
        if status_attribute_value != None:
            user_status = status_attribute_value.getValue()
            if StringHelper.equals(user_status, "inactive"):
                print "Basic (lock account). Lock user. User '%s' locked already" % user_name
                return
        
        userService.setCustomAttribute(find_user_by_uid, .jans.tatus", "inactive")
        userService.setCustomAttribute(find_user_by_uid, "oxTrustActive", "false")
        updated_user = userService.updateUser(find_user_by_uid)

        object_to_store = json.dumps({'locked': True, 'created': LocalDateTime.now().toString()}, separators=(',',':'))

        cacheService.put(StringHelper.toString(self.lockExpirationTime), "lock_user_"+user_name, object_to_store);
        facesMessages.add(FacesMessage.SEVERITY_ERROR, "Your account is locked. Please try again after " + StringHelper.toString(self.lockExpirationTime) + " secs")

        print "Basic (lock account). Lock user. User '%s' locked" % user_name
    def validateRecaptcha(self, recaptcha_response):
        print "Cert. Validate recaptcha response"

        facesContext = CdiUtil.bean(FacesContext)
        request = facesContext.getExternalContext().getRequest()

        remoteip = ServerUtil.getIpAddress(request)
        print "Cert. Validate recaptcha response. remoteip: '%s'" % remoteip

        httpService = CdiUtil.bean(HttpService)

        http_client = httpService.getHttpsClient()
        http_client_params = http_client.getParams()
        http_client_params.setIntParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT, 15 * 1000)

        recaptcha_validation_url = "https://www.google.com/recaptcha/api/siteverify"
        recaptcha_validation_request = urllib.urlencode({
            "secret":
            self.recaptcha_creds['secret_key'],
            "response":
            recaptcha_response,
            "remoteip":
            remoteip
        })
        recaptcha_validation_headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Accept": "application/json"
        }

        try:
            http_service_response = httpService.executePost(
                http_client, recaptcha_validation_url, None,
                recaptcha_validation_headers, recaptcha_validation_request)
            http_response = http_service_response.getHttpResponse()
        except:
            print "Cert. Validate recaptcha response. Exception: ", sys.exc_info(
            )[1]
            return False

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "Cert. Validate recaptcha response. Get invalid response from validation server: ", str(
                    http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return False

            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)
        finally:
            http_service_response.closeConnection()

        if response_string == None:
            print "Cert. Validate recaptcha response. Get empty response from validation server"
            return False

        response = json.loads(response_string)

        return response["success"]
Example #3
0
    def prepareForStep(self, configuration_attributes, request_parameters, step):
        print "ThumbSignIn. Inside prepareForStep. Step %d" % step
        identity = CdiUtil.bean(Identity)
        authentication_service = CdiUtil.bean(AuthenticationService)

        identity.setWorkingParameter("ts_host", ts_host)
        identity.setWorkingParameter("ts_statusPath", ts_statusPath)

        self.set_relying_party_login_url(identity)

        if step == 1 or step == 3:
            print "ThumbSignIn. Prepare for step 1"
            self.initialize_thumbsignin(identity, AUTHENTICATE)
            return True

        elif step == 2:
            print "ThumbSignIn. Prepare for step 2"
            if identity.isSetWorkingParameter(USER_LOGIN_FLOW):
                user_login_flow = identity.getWorkingParameter(USER_LOGIN_FLOW)
                print "ThumbSignIn. Value of user_login_flow is %s" % user_login_flow
            user = authentication_service.getAuthenticatedUser()
            if user is None:
                print "ThumbSignIn. Prepare for step 2. Failed to determine user name"
                return False
            user_name = user.getUserId()
            print "ThumbSignIn. Prepare for step 2. user_name: " + user_name
            if user_name is None:
                return False
            identity.setWorkingParameter(USER_ID, user_name)
            self.initialize_thumbsignin(identity, REGISTER + "/" + user_name)
            return True
        else:
            return False
    def createNewAuthenticatedSession(self, context, customParameters={}):
        sessionIdService = CdiUtil.bean(SessionIdService)

        user = context.getUser()
        client = CdiUtil.bean(Identity).getSessionClient().getClient()

        # Add mandatory session parameters
        sessionAttributes = HashMap()
        sessionAttributes.put(Constants.AUTHENTICATED_USER, user.getUserId())
        sessionAttributes.put(AuthorizeRequestParam.CLIENT_ID,
                              client.getClientId())
        sessionAttributes.put(AuthorizeRequestParam.PROMPT, "")

        # Add custom session parameters
        for key, value in customParameters.iteritems():
            if StringHelper.isNotEmpty(value):
                sessionAttributes.put(key, value)

        # Generate authenticated session
        sessionId = sessionIdService.generateAuthenticatedSessionId(
            context.getHttpRequest(), user.getDn(), sessionAttributes)

        print "ROPC script. Generated session id. DN: '%s'" % sessionId.getDn()

        return sessionId
Example #5
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        print "Casa. prepareForStep %s" % str(step)
        identity = CdiUtil.bean(Identity)

        if step == 1:
            self.prepareUIParams(identity)
            return True
        else:
            session_attributes = identity.getSessionId().getSessionAttributes()

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()

            if user == None:
                print "Casa. prepareForStep. Cannot retrieve logged user"
                return False

            acr = session_attributes.get("ACR")
            print "Casa. prepareForStep. ACR = %s" % acr
            identity.setWorkingParameter("methods", ArrayList(self.getAvailMethodsUser(user, acr)))

            if acr in self.authenticators:
                module = self.authenticators[acr]
                return module.prepareForStep(module.configAttrs, requestParameters, step)
            else:
                return False
Example #6
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)
        authenticationService = CdiUtil.bean(AuthenticationService)

        duo_host = configurationAttributes.get("duo_host").getValue2()

        if (step == 1):
            print "Duo. Prepare for step 1"

            return True
        elif (step == 2):
            print "Duo. Prepare for step 2"

            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "Duo. Prepare for step 2. Failed to determine user name"
                return False
            user_name = user.getUserId()

            duo_sig_request = duo_web.sign_request(self.ikey, self.skey,
                                                   self.akey, user_name)
            print "Duo. Prepare for step 2. duo_sig_request: " + duo_sig_request

            identity.setWorkingParameter("duo_host", duo_host)
            identity.setWorkingParameter("duo_sig_request", duo_sig_request)

            return True
        else:
            return False
Example #7
0
    def init(self, customScript, configurationAttributes):
        print "Application session. Initialization"

        self.entryManager = CdiUtil.bean(PersistenceEntryManager)
        self.staticConfiguration = CdiUtil.bean(StaticConfiguration)

        print "Application session. Initialized successfully"

        return True
Example #8
0
    def getNextStep(self, configurationAttributes, requestParameters, step):

        print "Casa. getNextStep called %s" % str(step)
        if step > 1:
            acr = ServerUtil.getFirstValue(requestParameters, "alternativeMethod")
            if acr != None:
                print "Casa. getNextStep. Use alternative method %s" % acr
                CdiUtil.bean(Identity).setWorkingParameter("ACR", acr)
                #retry step with different acr
                return 2

        return -1
Example #9
0
    def authenticate(self, configuration_attributes, request_parameters, step):
        print "ThumbSignIn. Inside authenticate. Step %d" % step
        authentication_service = CdiUtil.bean(AuthenticationService)
        identity = CdiUtil.bean(Identity)

        identity.setWorkingParameter("ts_host", ts_host)
        identity.setWorkingParameter("ts_statusPath", ts_statusPath)

        if step == 1 or step == 3:
            print "ThumbSignIn. Authenticate for Step %d" % step

            login_flow = ServerUtil.getFirstValue(request_parameters, "login_flow")
            print "ThumbSignIn. Value of login_flow parameter is %s" % login_flow

            # Logic for ThumbSignIn Authentication Flow (Either step 1 or step 3)
            if login_flow == THUMBSIGNIN_AUTHENTICATION or login_flow == THUMBSIGNIN_LOGIN_POST_REGISTRATION:
                identity.setWorkingParameter(USER_LOGIN_FLOW, login_flow)
                print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(USER_LOGIN_FLOW)
                logged_in_status = authentication_service.authenticate(self.get_user_id_from_thumbsignin(request_parameters))
                print "ThumbSignIn. logged_in status : %r" % logged_in_status
                return logged_in_status

            # Logic for traditional login flow (step 1)
            print "ThumbSignIn. User credentials login flow"
            identity.setWorkingParameter(USER_LOGIN_FLOW, THUMBSIGNIN_REGISTRATION)
            print "ThumbSignIn. Value of userLoginFlow is %s" % identity.getWorkingParameter(USER_LOGIN_FLOW)
            logged_in = self.authenticate_user_credentials(identity, authentication_service)
            print "ThumbSignIn. Status of User Credentials based Authentication : %r" % logged_in

            # When the traditional login fails, reinitialize the ThumbSignIn data before sending error response to UI
            if not logged_in:
                self.initialize_thumbsignin(identity, AUTHENTICATE)
                return False

            print "ThumbSignIn. Authenticate successful for step %d" % step
            return True

        elif step == 2:
            print "ThumbSignIn. Registration flow (step 2)"
            self.verify_user_login_flow(identity)

            user = self.get_authenticated_user_from.jans.authentication_service)
            if user is None:
                print "ThumbSignIn. Registration flow (step 2). Failed to determine user name"
                return False

            user_name = user.getUserId()
            print "ThumbSignIn. Registration flow (step 2) successful. user_name: %s" % user_name
            return True

        else:
            return False
Example #10
0
    def getCountAuthenticationSteps(self, configurationAttributes):
        print "Casa. getCountAuthenticationSteps called"

        if CdiUtil.bean(Identity).getWorkingParameter("skip2FA"):
           return 1

        acr = CdiUtil.bean(Identity).getWorkingParameter("ACR")
        if acr in self.authenticators:
            module = self.authenticators[acr]
            return module.getCountAuthenticationSteps(module.configAttrs)
        else:
            return 2

        print "Casa. getCountAuthenticationSteps. Could not determine the step count for acr %s" % acr
Example #11
0
    def prepareForStep(self, configurationAttributes, requestParameters, step):
        identity = CdiUtil.bean(Identity)

        if (step == 1):
            return True
        elif (step == 2):
            print "U2F. Prepare for step 2"

            session = CdiUtil.bean(SessionIdService).getSessionId()
            if session == None:
                print "U2F. Prepare for step 2. Failed to determine session_id"
                return False

            authenticationService = CdiUtil.bean(AuthenticationService)
            user = authenticationService.getAuthenticatedUser()
            if (user == None):
                print "U2F. Prepare for step 2. Failed to determine user name"
                return False

            u2f_application_id = configurationAttributes.get("u2f_application_id").getValue2()

            # Check if user have registered devices
            deviceRegistrationService = CdiUtil.bean(DeviceRegistrationService)

            userInum = user.getAttribute("inum")

            registrationRequest = None
            authenticationRequest = None

            deviceRegistrations = deviceRegistrationService.findUserDeviceRegistrations(userInum, u2f_application_id)
            if (deviceRegistrations.size() > 0):
                print "U2F. Prepare for step 2. Call FIDO U2F in order to start authentication workflow"

                try:
                    authenticationRequestService = FidoU2fClientFactory.instance().createAuthenticationRequestService(self.metaDataConfiguration)
                    authenticationRequest = authenticationRequestService.startAuthentication(user.getUserId(), None, u2f_application_id, session.getId())
                except ClientResponseFailure, ex:
                    if (ex.getResponse().getResponseStatus() != Response.Status.NOT_FOUND):
                        print "U2F. Prepare for step 2. Failed to start authentication workflow. Exception:", sys.exc_info()[1]
                        return False
            else:
                print "U2F. Prepare for step 2. Call FIDO U2F in order to start registration workflow"
                registrationRequestService = FidoU2fClientFactory.instance().createRegistrationRequestService(self.metaDataConfiguration)
                registrationRequest = registrationRequestService.startRegistration(user.getUserId(), u2f_application_id, session.getId())

            identity.setWorkingParameter("fido_u2f_authentication_request", ServerUtil.asJson(authenticationRequest))
            identity.setWorkingParameter("fido_u2f_registration_request", ServerUtil.asJson(registrationRequest))

            return True
Example #12
0
    def authenticate(self, configurationAttributes, requestParameters, step):
        if (step == 1):
            print "Yubicloud. Authenticate for step 1"

            identity = CdiUtil.bean(Identity)
            credentials = identity.getCredentials()

            username = credentials.getUsername()
            otp = credentials.getPassword()

            # Validate otp length
            if len(otp) < 32 or len(otp) > 48:
                print "Yubicloud. Invalid OTP length"
                return False

            user_service = CdiUtil.bean(UserService)
            user = user_service.getUser(username)

            public_key = user.getAttribute('yubikeyId')

            # Match the user with the yubikey
            if public_key not in otp:
                print "Yubicloud. Public Key not matching OTP"
                return False

            data = ""
            try:
                nonce = str(uuid.uuid4()).replace("-", "")
                params = urllib.urlencode({
                    "id": self.client_id,
                    "otp": otp,
                    "nonce": nonce
                })
                url = "https://" + self.api_server + "/wsapi/2.0/verify/?" + params
                f = urllib2.urlopen(url)
                data = f.read()
            except Exception as e:
                print "Yubicloud. Exception ", e

            if 'status=OK' in data:
                user_service.authenticate(username)
                print "Yubicloud. Authentication Successful"
                return True

            print "Yubicloud. End of Step 1. Returning False."
            return False
        else:
            return False
    def authenticate(self, context):
        print "ROPC script. Authenticate"

        # Do generic authentication
        authenticationService = CdiUtil.bean(AuthenticationService)

        username = context.getHttpRequest().getParameter("username")
        password = context.getHttpRequest().getParameter("password")
        result = authenticationService.authenticate(username, password)
        if not result:
            print "ROPC script. Authenticate. Could not authenticate user '%s' " % username
            return False

        context.setUser(authenticationService.getAuthenticatedUser())
        print "ROPC script. Authenticate. User '%s' authenticated successfully" % username

        # Get cusom parameters from request
        customParam1Value = context.getHttpRequest().getParameter("custom1")
        customParam2Value = context.getHttpRequest().getParameter("custom2")

        customParameters = {}
        customParameters["custom1"] = customParam1Value
        customParameters["custom2"] = customParam2Value
        print "ROPC script. Authenticate. User '%s'. Creating authenticated session with custom attributes: '%s'" % (
            username, customParameters)

        session = self.createNewAuthenticatedSession(context, customParameters)

        # This is needed to allow store in token entry sessionId
        authenticationService.configureEventUser(session)

        print "ROPC script. Authenticate. User '%s'. Created authenticated session: '%s'" % (
            username, customParameters)

        return True
    def confirmRegistration(self, user, requestParameters,
                            configurationAttributes):
        print "User Confirm registration. Confirm method"
        code_array = requestParameters.get("code")
        if ArrayHelper.isEmpty(code_array):
            print "User Confirm registration. Confirm method. code is empty"
            return False

        confirmation_code = code_array[0]
        print "User Confirm registration. Confirm method. code: '%s'" % confirmation_code

        if confirmation_code == None:
            print "User Confirm registration. Confirm method. Confirmation code not exist in request"
            return False

        personService = CdiUtil.bean(PersonService)
        user = personService.getPersonByAttribute("oxGuid", confirmation_code)
        if user == None:
            print "User Confirm registration. Confirm method. There is no user by confirmation code: '%s'" % confirmation_code
            return False

        if confirmation_code == user.getGuid():
            user.setStatus("active")
            user.setGuid("")
            personService.updatePerson(user)
            print "User Confirm registration. Confirm method. User '%s' confirmed his registration" % user.getUid(
            )
            return True

        print "User Confirm registration. Confirm method. Confirmation code for user '%s' is invalid" % user.getUid(
        )
        return False
    def update(self, dynamicScopeContext, configurationAttributes):
        print "Dynamic scope. Update method"
        userService = CdiUtil.bean(UserService)
        print "-->userService: " + userService.toString()

        dynamicScopes = dynamicScopeContext.getDynamicScopes()
        authorizationGrant = dynamicScopeContext.getAuthorizationGrant()
        user = dynamicScopeContext.getUser()
        jsonWebResponse = dynamicScopeContext.getJsonWebResponse()
        claims = jsonWebResponse.getClaims()

        member_of_list = userService.getCustomAttribute(user, "memberof")
        if member_of_list == None:
            print "-->memberOf: is null"
            return None
        else:
            members_list = member_of_list.getValues()
            membersArray = []
            for members in members_list:
                group = userService.getUserByDn(members, "displayName")
                membersArray.append(group.getAttribute("displayName"))

            claims.setClaim("memberof", Arrays.asList(membersArray))

        return True
    def update(self, dynamicScopeContext, configurationAttributes):
        print "Session dynamic scope. Update method"

        authorizationGrant = dynamicScopeContext.getAuthorizationGrant()

        if authorizationGrant is None:
            print "Introspection. Failed to load authorization grant by token"
            return False

        # Get session from token
        sessionDn = authorizationGrant.getSessionDn()
        if sessionDn is None:
            # There is no session
            return False

        sessionIdService = CdiUtil.bean(SessionIdService)
        session = sessionIdService.getSessionById(sessionDn)
        if session is None:
            print "Introspection. Failed to load session '%s'" % sessionDn
            return False

        sessionAttributes = session.getSessionAttributes()
        if sessionAttributes is None:
            # There is no session attributes
            return False

        # Return external_session_id
        externalSessionId = sessionAttributes.get("external_session_id")
        if externalSessionId != None:
            print "Introspection. Adding new claim 'external_session_id'  with value '%s'" % externalSessionId
            jsonWebResponse = dynamicScopeContext.getJsonWebResponse()
            claims = jsonWebResponse.getClaims()
            claims.setClaim("external_session_id", externalSessionId)

        return True
Example #17
0
    def executePost(self, request_uri, request_data):
        httpService = CdiUtil.bean(HttpService)

        request_headers = {
            "Content-type": "application/json; charset=UTF-8",
            "Accept": "application/json"
        }

        try:
            http_service_response = httpService.executePost(
                self.http_client, request_uri, None, request_headers,
                request_data)
            http_response = http_service_response.getHttpResponse()
        except:
            print "UAF. Validate POST response. Exception: ", sys.exc_info()[1]
            return None

        try:
            if not httpService.isResponseStastusCodeOk(http_response):
                print "UAF. Validate POST response. Get invalid response from  server: %s" % str(
                    http_response.getStatusLine().getStatusCode())
                httpService.consume(http_response)
                return None

            response_bytes = httpService.getResponseContent(http_response)
            response_string = httpService.convertEntityToString(response_bytes)
            httpService.consume(http_response)

            return response_string
        finally:
            http_service_response.closeConnection()
        return None
    def findEnrollments(self, user_name, skipPrefix=True):
        result = []

        userService = CdiUtil.bean(UserService)
        user = userService.getUser(user_name, "oxExternalUid")
        if user == None:
            print "OTP. Find enrollments. Failed to find user"
            return result

        user_custom_ext_attribute = userService.getCustomAttribute(
            user, "oxExternalUid")
        if user_custom_ext_attribute == None:
            return result

        otp_prefix = "%s:" % self.otpType

        otp_prefix_length = len(otp_prefix)
        for user_external_uid in user_custom_ext_attribute.getValues():
            index = user_external_uid.find(otp_prefix)
            if index != -1:
                if skipPrefix:
                    enrollment_uid = user_external_uid[otp_prefix_length:]
                else:
                    enrollment_uid = user_external_uid

                result.append(enrollment_uid)

        return result
Example #19
0
    def createClient(self, registerRequest, client, configurationAttributes):
        print "Client registration. CreateClient method"

        redirectUris = client.getRedirectUris()
        print "Client registration. Redirect Uris: %s" % redirectUris

        addAddressScope = False
        for redirectUri in redirectUris:
            if (self.clientRedirectUrisSet.contains(redirectUri)):
                addAddressScope = True
                break
        
        print "Client registration. Is add address scope: %s" % addAddressScope

        if addAddressScope:
            currentScopes = client.getScopes()
            print "Client registration. Current scopes: %s" % currentScopes
            
            scopeService = CdiUtil.bean(ScopeService)
            addressScope = scopeService.getScopeByDisplayName("address")
            newScopes = ArrayHelper.addItemToStringArray(currentScopes, addressScope.getDn())
    
            print "Client registration. Result scopes: %s" % newScopes
            client.setScopes(newScopes)

        return True
    def authenticate(self, context):
        print "ROPC script. Authenticate"
        deviceIdParam = context.getHttpRequest().getParameterValues(
            "device_id")
        if deviceIdParam != None and (deviceIdParam.lenght > 0):
            result = deviceIdParam[0] == "device_id_1"
            if not result:
                return False

            # Set auntenticated user in context
            # context.setUser(user)
            return True

        # Do generic authentication in other cases
        authService = CdiUtil.bean(AuthenticationService)

        username = context.getHttpRequest().getParameter(
            self.usernameParamName)
        password = context.getHttpRequest().getParameter(
            self.passwordParamName)
        result = authService.authenticate(username, password)
        if not result:
            print "ROPC script. Authenticate. Could not authenticate user '%s' " % username
            return False

        context.setUser(authService.getAuthenticatedUser())

        return True
Example #21
0
 def prepareUIParams(self, identity):
     
     print "Casa. prepareUIParams. Reading UI branding params"
     cacheService = CdiUtil.bean(CacheService)
     casaAssets = cacheService.get("casa_assets")
         
     if casaAssets == None:
         #This may happen when cache type is IN_MEMORY, where actual cache is merely a local variable 
         #(a expiring map) living inside Casa webapp, not oxAuth webapp
         
         sets = self.getSettings()
         
         custPrefix = "/custom"
         logoUrl = "/images/logo.png"
         faviconUrl = "/images/favicon.ico"
         if ("extra_css" in sets and sets["extra_css"] != None) or sets["use_branding"]:
             logoUrl = custPrefix + logoUrl
             faviconUrl = custPrefix + faviconUrl
         
         prefix = custPrefix if sets["use_branding"] else ""
         
         casaAssets = {
             "contextPath": "/casa",
             "prefix" : prefix,
             "faviconUrl" : faviconUrl,
             "extraCss": sets["extra_css"] if "extra_css" in sets else None,
             "logoUrl": logoUrl
         }
     
     #Setting a single variable with the whole map does not work...
     identity.setWorkingParameter("casa_contextPath", casaAssets['contextPath'])
     identity.setWorkingParameter("casa_prefix", casaAssets['prefix'])
     identity.setWorkingParameter("casa_faviconUrl", casaAssets['contextPath'] + casaAssets['faviconUrl'])
     identity.setWorkingParameter("casa_extraCss", casaAssets['extraCss'])
     identity.setWorkingParameter("casa_logoUrl", casaAssets['contextPath'] + casaAssets['logoUrl'])
Example #22
0
    def modifyResponse(self, responseAsJsonObject, context):
        token = context.getHttpRequest().getParameter("token")
        if token is None:
            print "Introspection. There is no token in request"
            return False

        authorizationGrantList = CdiUtil.bean(AuthorizationGrantList)
        authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(
            token)
        if authorizationGrant is None:
            print "Introspection. Failed to load authorization grant by token"
            return False

        # Put user_id into response
        responseAsJsonObject.accumulate(
            "user_id",
            authorizationGrant.getUser().getUserId())

        # Put custom parameters into response
        sessionDn = authorizationGrant.getSessionDn()
        if sessionDn is None:
            # There is no session
            return True

        sessionIdService = CdiUtil.bean(SessionIdService)
        session = sessionIdService.getSessionById(sessionDn)
        if sessionDn is None:
            print "Introspection. Failed to load session '%s'" % sessionDn
            return False

        # Return session_id
        responseAsJsonObject.accumulate("session_id", sessionDn)

        sessionAttributes = session.getSessionAttributes()
        if sessionAttributes is None:
            # There is no session attributes
            return True

        # Append custom claims
        if sessionAttributes.containsKey("custom1"):
            responseAsJsonObject.accumulate("custom1",
                                            sessionAttributes.get("custom1"))
        if sessionAttributes.containsKey("custom2"):
            responseAsJsonObject.accumulate("custom2",
                                            sessionAttributes.get("custom2"))

        return True
 def postRegistration(self, user, requestParameters,
                      configurationAttributes):
     print "User Confirm registration. Post method"
     externalContext = CdiUtil.bean(ExternalContext)
     contextPath = externalContext.getRequest().getContextPath()
     hostName = externalContext.getRequestServerName()
     print "HostName from context : %s" % hostName
     mailService = CdiUtil.bean(MailService)
     subject = "Registration confirmation"
     activationLink = "https://%s%s/confirm/registration.htm?code=%s" % (
         hostName, contextPath, self.guid)
     body = "<h2 style='margin-left:10%%;color: #337ab7;'>Welcome</h2><hr style='width:80%%;border: 1px solid #337ab7;'></hr><div style='text-align:center;'><p>Dear <span style='color: #337ab7;'>%s</span>,</p><p>Your Account has been created, welcome to <span style='color: #337ab7;'>%s</span>.</p><p>You are just one step way from activating your account on <span style='color: #337ab7;'>%s</span>.</p><p>Click the button and start using your account.</p></div><a class='btn' href='%s'><button style='background: #337ab7; color: white; margin-left: 30%%; border-radius: 5px; border: 0px; padding: 5px;' type='button'>Activate your account now!</button></a>" % (
         user.getUid(), hostName, hostName, activationLink)
     print "User Confirm registration. Post method. Attempting to send e-mail to '%s' message '%s'" % (
         user.getMail(), body)
     mailService.sendMail(user.getMail(), None, subject, body, body)
     return True
Example #24
0
 def updateUser(self, user, configurationAttributes):
     personService = CdiUtil.bean(PersonService)
     oldUser = personService.getPersonByUid(user.getUid())
     print "ScimEventHandler (updateUser): Old displayName %s" % oldUser.getDisplayName(
     )
     print "ScimEventHandler (updateUser): New displayName " + user.getDisplayName(
     )
     return True
    def getCountAuthenticationSteps(self, configurationAttributes):
        identity = CdiUtil.bean(Identity)

        if identity.isSetWorkingParameter("otp_count_login_steps"):
            return StringHelper.toInteger(
                "%s" % identity.getWorkingParameter("otp_count_login_steps"))
        else:
            return 2
Example #26
0
 def getLocalPrimaryKey(self):
     entryManager = CdiUtil.bean(PersistenceEntryManager)
     config = JanssenConfiguration()
     config = entryManager.find(config.getClass(), "ou=configuration,o.jans.)
     #Pick (one) attribute where user id is stored (e.g. uid/mail)
     uid_attr = config.getOxIDPAuthentication().get(0).getConfig().getPrimaryKey()
     print "Casa. init. uid attribute is '%s'" % uid_attr
     return uid_attr
    def initRecaptcha(self, configurationAttributes):
        print "Cert. Initialize recaptcha"
        if not configurationAttributes.containsKey("credentials_file"):
            return False

        cert_creds_file = configurationAttributes.get(
            "credentials_file").getValue2()

        # Load credentials from file
        f = open(cert_creds_file, 'r')
        try:
            creds = json.loads(f.read())
        except:
            print "Cert. Initialize recaptcha. Failed to load credentials from file: %s" % cert_creds_file
            return False
        finally:
            f.close()

        try:
            recaptcha_creds = creds["recaptcha"]
        except:
            print "Cert. Initialize recaptcha. Invalid credentials file '%s' format:" % cert_creds_file
            return False

        self.recaptcha_creds = None
        if recaptcha_creds["enabled"]:
            print "Cert. Initialize recaptcha. Recaptcha is enabled"

            encryptionService = CdiUtil.bean(EncryptionService)

            site_key = recaptcha_creds["site_key"]
            secret_key = recaptcha_creds["secret_key"]

            try:
                site_key = encryptionService.decrypt(site_key)
            except:
                # Ignore exception. Value is not encrypted
                print "Cert. Initialize recaptcha. Assuming that 'site_key' in not encrypted"

            try:
                secret_key = encryptionService.decrypt(secret_key)
            except:
                # Ignore exception. Value is not encrypted
                print "Cert. Initialize recaptcha. Assuming that 'secret_key' in not encrypted"

            self.recaptcha_creds = {
                'site_key': site_key,
                "secret_key": secret_key
            }
            print "Cert. Initialize recaptcha. Recaptcha is configured correctly"

            return True
        else:
            print "Cert. Initialize recaptcha. Recaptcha is disabled"

        return False
Example #28
0
 def getSettings(self):
     entryManager = CdiUtil.bean(PersistenceEntryManager)
     config = ApplicationConfiguration()
     config = entryManager.find(config.getClass(), "ou=casa,ou=configuration,o.jans.)
     settings = None
     try:
         settings = json.loads(config.getSettings())
     except:
         print "Casa. getSettings. Failed to parse casa settings from DB"
     return settings
Example #29
0
    def getCountAuthenticationSteps(self, configuration_attributes):
        print "ThumbSignIn. Inside getCountAuthenticationSteps.."
        identity = CdiUtil.bean(Identity)

        user_login_flow = identity.getWorkingParameter(USER_LOGIN_FLOW)
        print "ThumbSignIn. Value of userLoginFlow is %s" % user_login_flow
        if user_login_flow == THUMBSIGNIN_AUTHENTICATION:
            print "ThumbSignIn. Total Authentication Steps is: 1"
            return 1
        print "ThumbSignIn. Total Authentication Steps is: 3"
        return 3
 def getNextStep(self, configurationAttributes, requestParameters, step):
     print "getNextStep Invoked"
     # If user not pass current step change step to previous
     identity = CdiUtil.bean(Identity)
     retry_current_step = identity.getWorkingParameter("retry_current_step")
     if retry_current_step:
         print "OTP. Get next step. Retrying current step %s" % step
         # Remove old QR code
         #identity.setWorkingParameter("super.jans.request", "timeout")
         resultStep = step
         return resultStep
     return -1