arvind_gluu

passport username email fixed

Oct 10th, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.24 KB | None | 0 0
  1. # oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
  2. # Copyright (c) 2016, Gluu
  3. #
  4. # Author: Arvind Tomar
  5. #
  6.  
  7. from org.xdi.service.cdi.util import CdiUtil
  8. from org.gluu.jsf2.message import FacesMessages
  9. from javax.faces.application import FacesMessage
  10. from org.xdi.util import StringHelper, ArrayHelper
  11. from java.util import Arrays, ArrayList, HashMap, IdentityHashMap
  12. from org.xdi.oxauth.client import TokenClient, TokenRequest, UserInfoClient
  13. from org.xdi.oxauth.model.common import GrantType, AuthenticationMethod
  14. from org.xdi.oxauth.model.jwt import Jwt, JwtClaimName
  15. from org.xdi.oxauth.security import Identity
  16. from org.xdi.model.custom.script.type.auth import PersonAuthenticationType
  17. from org.xdi.oxauth.service import UserService, ClientService, AuthenticationService
  18. from org.xdi.oxauth.model.common import User
  19. from org.xdi.util import StringHelper
  20. from org.xdi.oxauth.util import ServerUtil
  21. from org.gluu.jsf2.service import FacesService
  22. from org.xdi.oxauth.model.util import Base64Util
  23. from org.python.core.util import StringUtil
  24. from org.xdi.oxauth.service.net import HttpService
  25. from java.util import HashMap
  26. from org.apache.http.params import CoreConnectionPNames
  27.  
  28. import json
  29. import java
  30.  
  31.  
  32. class PersonAuthentication(PersonAuthenticationType):
  33.     def __init__(self, currentTimeMillis):
  34.         self.currentTimeMillis = currentTimeMillis
  35.  
  36.     print "Passport: Basic. Initialized successfully"
  37.  
  38.     def init(self, configurationAttributes):
  39.         print "Passport: Basic. Initialization init method call"
  40.         self.extensionModule = None
  41.         self.attributesMapping = None
  42.         if (configurationAttributes.containsKey("generic_remote_attributes_list") and
  43.                 configurationAttributes.containsKey("generic_local_attributes_list")):
  44.  
  45.             remoteAttributesList = configurationAttributes.get("generic_remote_attributes_list").getValue2()
  46.             if (StringHelper.isEmpty(remoteAttributesList)):
  47.                 print "Passport: Initialization. The property generic_remote_attributes_list is empty"
  48.                 return False
  49.  
  50.             localAttributesList = configurationAttributes.get("generic_local_attributes_list").getValue2()
  51.             if (StringHelper.isEmpty(localAttributesList)):
  52.                 print "Passport: Initialization. The property generic_local_attributes_list is empty"
  53.                 return False
  54.  
  55.             self.attributesMapping = self.prepareAttributesMapping(remoteAttributesList, localAttributesList)
  56.             if (self.attributesMapping == None):
  57.                 print "Passport: Initialization. The attributes mapping isn't valid"
  58.                 return False
  59.  
  60.         if (configurationAttributes.containsKey("extension_module")):
  61.             extensionModuleName = configurationAttributes.get("extension_module").getValue2()
  62.             try:
  63.                 self.extensionModule = __import__(extensionModuleName)
  64.                 extensionModuleInitResult = self.extensionModule.init(configurationAttributes)
  65.                 if (not extensionModuleInitResult):
  66.                     return False
  67.             except ImportError, ex:
  68.                 print "Passport: Initialization. Failed to load generic_extension_module:", extensionModuleName
  69.                 print "Passport: Initialization. Unexpected error:", ex
  70.                 return False
  71.         else:
  72.             print("Passport: Extension module key not found")
  73.         return True
  74.  
  75.     def destroy(self, configurationAttributes):
  76.         print "Passport: Basic. Destroy method call"
  77.         print "Passport: Basic. Destroyed successfully"
  78.         return True
  79.  
  80.     def getApiVersion(self):
  81.         return 1
  82.  
  83.     def isValidAuthenticationMethod(self, usageType, configurationAttributes):
  84.         return True
  85.  
  86.     def getAlternativeAuthenticationMethod(self, usageType, configurationAttributes):
  87.         return None
  88.  
  89.     def getUserValueFromAuth(self, remote_attr, requestParameters):
  90.         try:
  91.             toBeFeatched = "loginForm:" + remote_attr
  92.             return ServerUtil.getFirstValue(requestParameters, toBeFeatched)
  93.         except Exception, err:
  94.             print("Passport: Exception inside getUserValueFromAuth " + str(err))
  95.  
  96.     def authenticate(self, configurationAttributes, requestParameters, step):
  97.         extensionResult = self.extensionAuthenticate(configurationAttributes, requestParameters, step)
  98.         if extensionResult != None:
  99.             return extensionResult
  100.  
  101.         authenticationService = CdiUtil.bean(AuthenticationService)
  102.  
  103.         try:
  104.             UserId = self.getUserValueFromAuth("userid", requestParameters)
  105.         except Exception, err:
  106.             print("Passport: Error: " + str(err))
  107.         useBasicAuth = False
  108.         if (StringHelper.isEmptyString(UserId)):
  109.             useBasicAuth = True
  110.  
  111.         # Use basic method to log in
  112.         if (useBasicAuth):
  113.             print "Passport: Basic Authentication"
  114.             identity = CdiUtil.bean(Identity)
  115.             credentials = identity.getCredentials()
  116.  
  117.             user_name = credentials.getUsername()
  118.             user_password = credentials.getPassword()
  119.  
  120.             logged_in = False
  121.             if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
  122.                 userService = CdiUtil.bean(UserService)
  123.                 logged_in = authenticationService.authenticate(user_name, user_password)
  124.  
  125.             if (not logged_in):
  126.                 return False
  127.             return True
  128.  
  129.         else:
  130.             try:
  131.                 userService = CdiUtil.bean(UserService)
  132.                 authenticationService = CdiUtil.bean(AuthenticationService)
  133.                 foundUser = userService.getUserByAttribute("oxExternalUid", self.getUserValueFromAuth("provider",
  134.                                                                                                       requestParameters) + ":" + self.getUserValueFromAuth(
  135.                     self.getUidRemoteAttr(), requestParameters))
  136.                 if (foundUser == None):
  137.                     foundUser = userService.getUserByAttribute("mail", self.getUserValueFromAuth(
  138.                         "email", requestParameters))
  139.  
  140.                 if (foundUser == None):
  141.                     foundUser = userService.getUserByAttribute("uid", self.getUserValueFromAuth(
  142.                         "username", requestParameters))
  143.                     print  self.getUserValueFromAuth("username", requestParameters)
  144.  
  145.  
  146.                 if (foundUser == None):
  147.                     newUser = User()
  148.  
  149.                     try:
  150.                         UserEmail = self.getUserValueFromAuth("email", requestParameters)
  151.                     except Exception, err:
  152.                         print("Passport: Error in getting user email: " + str(err))
  153.  
  154.                     if (StringHelper.isEmptyString(UserEmail)):
  155.                         facesMessages = CdiUtil.bean(FacesMessages)
  156.                         facesMessages.setKeepMessages()
  157.                         facesMessages.clear()
  158.                         facesMessages.add(FacesMessage.SEVERITY_ERROR, "Please provide your email.")
  159.                         print "Passport: Email was not received so sent error"
  160.  
  161.                         return False
  162.  
  163.                     for attributesMappingEntry in self.attributesMapping.entrySet():
  164.                         remoteAttribute = attributesMappingEntry.getKey()
  165.                         localAttribute = attributesMappingEntry.getValue()
  166.                         localAttributeValue = self.getUserValueFromAuth(remoteAttribute, requestParameters)
  167.                         if ((localAttribute != None) & (localAttributeValue != "undefined") & (
  168.                                     localAttribute != "provider")):
  169.                             newUser.setAttribute(localAttribute, localAttributeValue)
  170.                     newUser.setAttribute("oxExternalUid", self.getUserValueFromAuth("provider",
  171.                                                                                     requestParameters) + ":" + self.getUserValueFromAuth(
  172.                         self.getUidRemoteAttr(), requestParameters))
  173.                     print ("Passport: " + self.getUserValueFromAuth("provider",
  174.                                                                     requestParameters) + ": Attempting to add user " + self.getUserValueFromAuth(
  175.                         self.getUidRemoteAttr(), requestParameters))
  176.  
  177.                     try:
  178.                         foundUser = userService.addUser(newUser, True)
  179.                         foundUserName = foundUser.getUserId()
  180.                         print("Passport: Found user name " + foundUserName)
  181.                         userAuthenticated = authenticationService.authenticate(foundUserName)
  182.                         print("Passport: User added successfully and isUserAuthenticated = " + str(userAuthenticated))
  183.                     except Exception, err:
  184.                         print("Passport: Error in adding user:" + str(err))
  185.                         return False
  186.                     return userAuthenticated
  187.  
  188.  
  189.  
  190.                 else:
  191.                     foundUserName = foundUser.getUserId()
  192.                     print("Passport: User Found " + str(foundUserName))
  193.                     userAuthenticated = authenticationService.authenticate(foundUserName)
  194.                     print("Passport: Is user authenticated = " + str(userAuthenticated))
  195.                     return True
  196.  
  197.             except Exception, err:
  198.                 print ("Passport: Error occurred during request parameter fetching " + str(err))
  199.  
  200.     def prepareForStep(self, configurationAttributes, requestParameters, step):
  201.         extensionResult = self.extensionPrepareForStep(configurationAttributes, requestParameters, step)
  202.         if extensionResult != None:
  203.             return extensionResult
  204.  
  205.         if (step == 1):
  206.             try:
  207.                 print "Passport: Basic. Prepare for Step 1 method call"
  208.                 identity = CdiUtil.bean(Identity)
  209.                 sessionId = identity.getSessionId()
  210.                 sessionAttribute = sessionId.getSessionAttributes()
  211.                 print "session"
  212.  
  213.                 oldState = sessionAttribute.get("state")
  214.                 if (oldState == None):
  215.                     return True
  216.                 stateBytes = Base64Util.base64urldecode(oldState)
  217.                 state = StringUtil.fromBytes(stateBytes)
  218.                 print "state %s" % state
  219.                 stateObj = json.loads(state)
  220.                 print stateObj["provider"]
  221.                 for y in stateObj:
  222.                     print (y, ':', stateObj[y])
  223.  
  224.                 # facesService = CdiUtil.bean(FacesService)
  225.                 token = self.getPassportToken(configurationAttributes)
  226.                 print "/passport/auth/" + stateObj["provider"] + "/" + token
  227.                 # facesService.redirectToExternalURL(
  228.                 #     "https://gluu.evp.org/passport/auth/" + stateObj["provider"] + "/" + token,)
  229.  
  230.                 redirect_uri = "https://gluu.evp.org/passport/auth/" + stateObj["provider"] + "/" + token
  231.                 identity = CdiUtil.bean(Identity)
  232.                 identity.setWorkingParameter("passport_redirect_uri", redirect_uri)
  233.  
  234.                 session_attributes = identity.getSessionId().getSessionAttributes()
  235.                 session_attributes.put("passport_redirect_uri", redirect_uri)
  236.                 # if session_attributes.containsKey("passport_redirect_uri"):
  237.                 #     redirect_uri = session_attributes.get("passport_redirect_uri")
  238.                 #     print ("passport_access_token from session" + redirect_uri)
  239.                 #     return Arrays.asList(token)
  240.  
  241.             except Exception, err:
  242.                 print("Passport: Exception inside passportTOken " + str(err))
  243.             return True
  244.         else:
  245.             return True
  246.  
  247.     def getPassportToken(self, configurationAttributes):
  248.         # if (configurationAttributes.containsKey("host")):
  249.         #     url = configurationAttributes.get("host").getValue2() + "/passport/token"
  250.         url = 'https://gluu.evp.org/passport/token'
  251.         httpService = CdiUtil.bean(HttpService)
  252.  
  253.         http_client = httpService.getHttpsClient()
  254.  
  255.         print ("token passport url " + url)
  256.  
  257.         try:
  258.             http_service_response = httpService.executeGet(http_client, url)
  259.             http_response = http_service_response.getHttpResponse()
  260.             http_client_params = http_client.getParams()
  261.             http_client_params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 500)
  262.  
  263.             token = json.loads(httpService.convertEntityToString(httpService.getResponseContent(http_response)))[
  264.                 'token_'];
  265.             print ("token from passport server " + token)
  266.             return token
  267.         except Exception, err:
  268.             print "Fetching passport token from passport server Exception: " + err
  269.             return None
  270.  
  271.     def getExtraParametersForStep(self, configurationAttributes, step):
  272.         return None
  273.  
  274.     def getCountAuthenticationSteps(self, configurationAttributes):
  275.         return 1
  276.  
  277.     def getPageForStep(self, configurationAttributes, step):
  278.         extensionResult = self.extensionGetPageForStep(configurationAttributes, step)
  279.         if extensionResult != None:
  280.             return extensionResult
  281.  
  282.         if (step == 1):
  283.             return "/auth/passport/passportlogin.xhtml"
  284.         return "/auth/passport/passportpostlogin.xhtml"
  285.  
  286.     def logout(self, configurationAttributes, requestParameters):
  287.         return True
  288.  
  289.     def prepareAttributesMapping(self, remoteAttributesList, localAttributesList):
  290.         try:
  291.             remoteAttributesListArray = StringHelper.split(remoteAttributesList, ",")
  292.             if (ArrayHelper.isEmpty(remoteAttributesListArray)):
  293.                 print(
  294.                     "Passport: PrepareAttributesMapping. There is no attributes specified in remoteAttributesList property")
  295.                 return None
  296.  
  297.             localAttributesListArray = StringHelper.split(localAttributesList, ",")
  298.             if (ArrayHelper.isEmpty(localAttributesListArray)):
  299.                 print(
  300.                     "Passport: PrepareAttributesMapping. There is no attributes specified in localAttributesList property")
  301.                 return None
  302.  
  303.             if (len(remoteAttributesListArray) != len(localAttributesListArray)):
  304.                 print(
  305.                     "Passport: PrepareAttributesMapping. The number of attributes in remoteAttributesList and localAttributesList isn't equal")
  306.                 return None
  307.  
  308.             attributeMapping = IdentityHashMap()
  309.             containsUid = False
  310.             i = 0
  311.             count = len(remoteAttributesListArray)
  312.             while (i < count):
  313.                 remoteAttribute = StringHelper.toLowerCase(remoteAttributesListArray[i])
  314.                 localAttribute = StringHelper.toLowerCase(localAttributesListArray[i])
  315.                 attributeMapping.put(remoteAttribute, localAttribute)
  316.                 if (StringHelper.equalsIgnoreCase(localAttribute, "uid")):
  317.                     containsUid = True
  318.  
  319.                 i = i + 1
  320.  
  321.             if (not containsUid):
  322.                 print "Passport: PrepareAttributesMapping. There is no mapping to mandatory 'uid' attribute"
  323.                 return None
  324.  
  325.             return attributeMapping
  326.         except Exception, err:
  327.             print("Passport: Exception inside prepareAttributesMapping " + str(err))
  328.  
  329.     def getUidRemoteAttr(self):
  330.         try:
  331.             for attributesMappingEntry in self.attributesMapping.entrySet():
  332.                 remoteAttribute = attributesMappingEntry.getKey()
  333.                 localAttribute = attributesMappingEntry.getValue()
  334.                 if localAttribute == "uid":
  335.                     return remoteAttribute
  336.             else:
  337.                 return "Not Get UID related remote attribute"
  338.         except Exception, err:
  339.             print("Passport: Exception inside getUidRemoteAttr " + str(err))
  340.  
  341.     def extensionAuthenticate(self, configurationAttributes, requestParameters, step):
  342.         if (self.extensionModule == None):
  343.             return None
  344.  
  345.         try:
  346.             result = self.extensionModule.authenticate(configurationAttributes, requestParameters, step)
  347.             print "Passport. Extension. Authenticate: '%s'" % result
  348.  
  349.             return result
  350.         except Exception, ex:
  351.             print "Passport. Extension. Authenticate. Failed to execute postLogin method"
  352.             print "Passport. Extension. Authenticate. Unexpected error:", ex
  353.         except java.lang.Throwable, ex:
  354.             print "Passport. Extension. Authenticate. Failed to execute postLogin method"
  355.             ex.printStackTrace()
  356.  
  357.         return True
  358.  
  359.     def extensionGetPageForStep(self, configurationAttributes, step):
  360.         if (self.extensionModule == None):
  361.             return None
  362.  
  363.         try:
  364.             result = self.extensionModule.getPageForStep(configurationAttributes, step)
  365.             print "Passport. Extension. Get page for Step: '%s'" % result
  366.  
  367.             return result
  368.         except Exception, ex:
  369.             print "Passport. Extension. Get page for Step. Failed to execute postLogin method"
  370.             print "Passport. Extension. Get page for Step. Unexpected error:", ex
  371.         except java.lang.Throwable, ex:
  372.             print "Passport. Extension. Get page for Step. Failed to execute postLogin method"
  373.             ex.printStackTrace()
  374.  
  375.         return None
  376.  
  377.     def extensionPrepareForStep(self, configurationAttributes, requestParameters, step):
  378.         if (self.extensionModule == None):
  379.             return None
  380.  
  381.         try:
  382.             result = self.extensionModule.prepareForStep(configurationAttributes, requestParameters, step)
  383.             print "Passport. Extension. Prepare for Step: '%s'" % result
  384.  
  385.             return result
  386.         except Exception, ex:
  387.             print "Passport. Extension. Prepare for Step. Failed to execute postLogin method"
  388.             print "Passport. Extension. Prepare for Step. Unexpected error:", ex
  389.         except java.lang.Throwable, ex:
  390.             print "Passport. Extension. Prepare for Step. Failed to execute postLogin method"
  391.             ex.printStackTrace()
  392.  
  393.         return None
Add Comment
Please, Sign In to add comment