Advertisement
arvind_gluu

Passport fix for email merge

Nov 2nd, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.02 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.  
  22. import json
  23. import java
  24.  
  25.  
  26. class PersonAuthentication(PersonAuthenticationType):
  27.     def __init__(self, currentTimeMillis):
  28.         self.currentTimeMillis = currentTimeMillis
  29.  
  30.     print "Passport: Basic. Initialized successfully"
  31.  
  32.     def init(self, configurationAttributes):
  33.         print "Passport: Basic. Initialization init method call"
  34.         self.extensionModule = None
  35.         self.attributesMapping = None
  36.         if (configurationAttributes.containsKey("generic_remote_attributes_list") and
  37.                 configurationAttributes.containsKey("generic_local_attributes_list")):
  38.  
  39.             remoteAttributesList = configurationAttributes.get("generic_remote_attributes_list").getValue2()
  40.             if (StringHelper.isEmpty(remoteAttributesList)):
  41.                 print "Passport: Initialization. The property generic_remote_attributes_list is empty"
  42.                 return False
  43.  
  44.             localAttributesList = configurationAttributes.get("generic_local_attributes_list").getValue2()
  45.             if (StringHelper.isEmpty(localAttributesList)):
  46.                 print "Passport: Initialization. The property generic_local_attributes_list is empty"
  47.                 return False
  48.  
  49.             self.attributesMapping = self.prepareAttributesMapping(remoteAttributesList, localAttributesList)
  50.             if (self.attributesMapping == None):
  51.                 print "Passport: Initialization. The attributes mapping isn't valid"
  52.                 return False
  53.  
  54.         if (configurationAttributes.containsKey("extension_module")):
  55.             extensionModuleName = configurationAttributes.get("extension_module").getValue2()
  56.             try:
  57.                 self.extensionModule = __import__(extensionModuleName)
  58.                 extensionModuleInitResult = self.extensionModule.init(configurationAttributes)
  59.                 if (not extensionModuleInitResult):
  60.                     return False
  61.             except ImportError, ex:
  62.                 print "Passport: Initialization. Failed to load generic_extension_module:", extensionModuleName
  63.                 print "Passport: Initialization. Unexpected error:", ex
  64.                 return False
  65.         else:
  66.             print("Passport: Extension module key not found")
  67.         return True
  68.  
  69.     def destroy(self, configurationAttributes):
  70.         print "Passport: Basic. Destroy method call"
  71.         print "Passport: Basic. Destroyed successfully"
  72.         return True
  73.  
  74.     def getApiVersion(self):
  75.         return 1
  76.  
  77.     def isValidAuthenticationMethod(self, usageType, configurationAttributes):
  78.         return True
  79.  
  80.     def getAlternativeAuthenticationMethod(self, usageType, configurationAttributes):
  81.         return None
  82.  
  83.     def getUserValueFromAuth(self, remote_attr, requestParameters):
  84.         try:
  85.             toBeFeatched = "loginForm:" + remote_attr
  86.             return ServerUtil.getFirstValue(requestParameters, toBeFeatched)
  87.         except Exception, err:
  88.             print("Passport: Exception inside getUserValueFromAuth " + str(err))
  89.  
  90.     def authenticate(self, configurationAttributes, requestParameters, step):
  91.         extensionResult = self.extensionAuthenticate(configurationAttributes, requestParameters, step)
  92.         if extensionResult != None:
  93.             return extensionResult
  94.  
  95.         authenticationService = CdiUtil.bean(AuthenticationService)
  96.  
  97.         try:
  98.             UserId = self.getUserValueFromAuth("userid", requestParameters)
  99.         except Exception, err:
  100.             print("Passport: Error: " + str(err))
  101.         useBasicAuth = False
  102.         if (StringHelper.isEmptyString(UserId)):
  103.             useBasicAuth = True
  104.  
  105.         # Use basic method to log in
  106.         if (useBasicAuth):
  107.             print "Passport: Basic Authentication"
  108.             identity = CdiUtil.bean(Identity)
  109.             credentials = identity.getCredentials()
  110.  
  111.             user_name = credentials.getUsername()
  112.             user_password = credentials.getPassword()
  113.  
  114.             logged_in = False
  115.             if (StringHelper.isNotEmptyString(user_name) and StringHelper.isNotEmptyString(user_password)):
  116.                 userService = CdiUtil.bean(UserService)
  117.                 logged_in = authenticationService.authenticate(user_name, user_password)
  118.  
  119.             if (not logged_in):
  120.                 return False
  121.             return True
  122.  
  123.         else:
  124.             try:
  125.                 userService = CdiUtil.bean(UserService)
  126.                 authenticationService = CdiUtil.bean(AuthenticationService)
  127.                 foundUser = userService.getUserByAttribute("oxExternalUid", self.getUserValueFromAuth("provider",
  128.                                                                                                       requestParameters) + ":" + self.getUserValueFromAuth(
  129.                     self.getUidRemoteAttr(), requestParameters))
  130.                 if (foundUser == None):
  131.                     foundUser = userService.getUserByAttribute("mail", self.getUserValueFromAuth(
  132.                         "email", requestParameters))
  133.  
  134.                 if (foundUser == None):
  135.                     foundUser = userService.getUserByAttribute("uid", self.getUserValueFromAuth(
  136.                         "username", requestParameters))
  137.                     print  self.getUserValueFromAuth("username", requestParameters)
  138.  
  139.                 if (foundUser == None):
  140.                     newUser = User()
  141.  
  142.                     try:
  143.                         UserEmail = self.getUserValueFromAuth("email", requestParameters)
  144.                     except Exception, err:
  145.                         print("Passport: Error in getting user email: " + str(err))
  146.  
  147.                     if (StringHelper.isEmptyString(UserEmail)):
  148.                         facesMessages = CdiUtil.bean(FacesMessages)
  149.                         facesMessages.setKeepMessages()
  150.                         facesMessages.clear()
  151.                         facesMessages.add(FacesMessage.SEVERITY_ERROR, "Please provide your email.")
  152.                         print "Passport: Email was not received so sent error"
  153.  
  154.                         return False
  155.  
  156.                     for attributesMappingEntry in self.attributesMapping.entrySet():
  157.                         remoteAttribute = attributesMappingEntry.getKey()
  158.                         localAttribute = attributesMappingEntry.getValue()
  159.                         localAttributeValue = self.getUserValueFromAuth(remoteAttribute, requestParameters)
  160.                         if ((localAttribute != None) & (localAttributeValue != "undefined") & (
  161.                                     localAttribute != "provider")):
  162.                             newUser.setAttribute(localAttribute, localAttributeValue)
  163.                     newUser.setAttribute("oxExternalUid", self.getUserValueFromAuth("provider",
  164.                                                                                     requestParameters) + ":" + self.getUserValueFromAuth(
  165.                         self.getUidRemoteAttr(), requestParameters))
  166.                     print ("Passport: " + self.getUserValueFromAuth("provider",
  167.                                                                     requestParameters) + ": Attempting to add user " + self.getUserValueFromAuth(
  168.                         self.getUidRemoteAttr(), requestParameters))
  169.  
  170.                     try:
  171.                         foundUser = userService.addUser(newUser, True)
  172.                         foundUserName = foundUser.getUserId()
  173.                         print("Passport: Found user name " + foundUserName)
  174.                         userAuthenticated = authenticationService.authenticate(foundUserName)
  175.                         print("Passport: User added successfully and isUserAuthenticated = " + str(userAuthenticated))
  176.                     except Exception, err:
  177.                         print("Passport: Error in adding user:" + str(err))
  178.                         return False
  179.                     return userAuthenticated
  180.  
  181.                 else:
  182.                     foundUserName = foundUser.getUserId()
  183.                     print("Passport: User Found " + str(foundUserName))
  184.                     userAuthenticated = authenticationService.authenticate(foundUserName)
  185.                     print("Passport: Is user authenticated = " + str(userAuthenticated))
  186.                     return True
  187.  
  188.             except Exception, err:
  189.                 print ("Passport: Error occurred during request parameter fetching " + str(err))
  190.  
  191.     def prepareForStep(self, configurationAttributes, requestParameters, step):
  192.         extensionResult = self.extensionPrepareForStep(configurationAttributes, requestParameters, step)
  193.         if extensionResult != None:
  194.             return extensionResult
  195.  
  196.         if (step == 1):
  197.             print "Passport. Prepare for Step 1 method call"
  198.             return True
  199.         else:
  200.             return True
  201.  
  202.     def getExtraParametersForStep(self, configurationAttributes, step):
  203.         return None
  204.  
  205.     def getCountAuthenticationSteps(self, configurationAttributes):
  206.         return 1
  207.  
  208.     def getPageForStep(self, configurationAttributes, step):
  209.         extensionResult = self.extensionGetPageForStep(configurationAttributes, step)
  210.         if extensionResult != None:
  211.             return extensionResult
  212.  
  213.         if (step == 1):
  214.             return "/auth/passport/passportlogin.xhtml"
  215.         return "/auth/passport/passportpostlogin.xhtml"
  216.  
  217.     def logout(self, configurationAttributes, requestParameters):
  218.         return True
  219.  
  220.     def prepareAttributesMapping(self, remoteAttributesList, localAttributesList):
  221.         try:
  222.             remoteAttributesListArray = StringHelper.split(remoteAttributesList, ",")
  223.             if (ArrayHelper.isEmpty(remoteAttributesListArray)):
  224.                 print(
  225.                     "Passport: PrepareAttributesMapping. There is no attributes specified in remoteAttributesList property")
  226.                 return None
  227.  
  228.             localAttributesListArray = StringHelper.split(localAttributesList, ",")
  229.             if (ArrayHelper.isEmpty(localAttributesListArray)):
  230.                 print(
  231.                     "Passport: PrepareAttributesMapping. There is no attributes specified in localAttributesList property")
  232.                 return None
  233.  
  234.             if (len(remoteAttributesListArray) != len(localAttributesListArray)):
  235.                 print(
  236.                     "Passport: PrepareAttributesMapping. The number of attributes in remoteAttributesList and localAttributesList isn't equal")
  237.                 return None
  238.  
  239.             attributeMapping = IdentityHashMap()
  240.             containsUid = False
  241.             i = 0
  242.             count = len(remoteAttributesListArray)
  243.             while (i < count):
  244.                 remoteAttribute = StringHelper.toLowerCase(remoteAttributesListArray[i])
  245.                 localAttribute = StringHelper.toLowerCase(localAttributesListArray[i])
  246.                 attributeMapping.put(remoteAttribute, localAttribute)
  247.                 if (StringHelper.equalsIgnoreCase(localAttribute, "uid")):
  248.                     containsUid = True
  249.  
  250.                 i = i + 1
  251.  
  252.             if (not containsUid):
  253.                 print "Passport: PrepareAttributesMapping. There is no mapping to mandatory 'uid' attribute"
  254.                 return None
  255.  
  256.             return attributeMapping
  257.         except Exception, err:
  258.             print("Passport: Exception inside prepareAttributesMapping " + str(err))
  259.  
  260.     def getUidRemoteAttr(self):
  261.         try:
  262.             for attributesMappingEntry in self.attributesMapping.entrySet():
  263.                 remoteAttribute = attributesMappingEntry.getKey()
  264.                 localAttribute = attributesMappingEntry.getValue()
  265.                 if localAttribute == "uid":
  266.                     return remoteAttribute
  267.             else:
  268.                 return "Not Get UID related remote attribute"
  269.         except Exception, err:
  270.             print("Passport: Exception inside getUidRemoteAttr " + str(err))
  271.  
  272.     def extensionAuthenticate(self, configurationAttributes, requestParameters, step):
  273.         if (self.extensionModule == None):
  274.             return None
  275.  
  276.         try:
  277.             result = self.extensionModule.authenticate(configurationAttributes, requestParameters, step)
  278.             print "Passport. Extension. Authenticate: '%s'" % result
  279.  
  280.             return result
  281.         except Exception, ex:
  282.             print "Passport. Extension. Authenticate. Failed to execute postLogin method"
  283.             print "Passport. Extension. Authenticate. Unexpected error:", ex
  284.         except java.lang.Throwable, ex:
  285.             print "Passport. Extension. Authenticate. Failed to execute postLogin method"
  286.             ex.printStackTrace()
  287.  
  288.         return True
  289.  
  290.     def extensionGetPageForStep(self, configurationAttributes, step):
  291.         if (self.extensionModule == None):
  292.             return None
  293.  
  294.         try:
  295.             result = self.extensionModule.getPageForStep(configurationAttributes, step)
  296.             print "Passport. Extension. Get page for Step: '%s'" % result
  297.  
  298.             return result
  299.         except Exception, ex:
  300.             print "Passport. Extension. Get page for Step. Failed to execute postLogin method"
  301.             print "Passport. Extension. Get page for Step. Unexpected error:", ex
  302.         except java.lang.Throwable, ex:
  303.             print "Passport. Extension. Get page for Step. Failed to execute postLogin method"
  304.             ex.printStackTrace()
  305.  
  306.         return None
  307.  
  308.     def extensionPrepareForStep(self, configurationAttributes, requestParameters, step):
  309.         if (self.extensionModule == None):
  310.             return None
  311.  
  312.         try:
  313.             result = self.extensionModule.prepareForStep(configurationAttributes, requestParameters, step)
  314.             print "Passport. Extension. Prepare for Step: '%s'" % result
  315.  
  316.             return result
  317.         except Exception, ex:
  318.             print "Passport. Extension. Prepare for Step. Failed to execute postLogin method"
  319.             print "Passport. Extension. Prepare for Step. Unexpected error:", ex
  320.         except java.lang.Throwable, ex:
  321.             print "Passport. Extension. Prepare for Step. Failed to execute postLogin method"
  322.             ex.printStackTrace()
  323.  
  324.         return None
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement