Ejemplo n.º 1
0
 def generateUserToken(user_id: str):
     """
     Creates a token for a specific user.
     Removes any token previously created for the user.
     """
     response = ApiResponse()
     user = User.query.filter_by(id=user_id).first()
     timestamp = time.time()
     timestamp_millis = int(round(timestamp * 1000))
     token_ids = sha256(hash_id(timestamp_millis + randint(0, 9999)))
     token_value = sha256(hash_id(timestamp_millis) + str(uuid4()))
     expires_at = int(timestamp + TOKEN_EXPIRATION_TIME)
     if user:
         token = Token(ids=token_ids,
                       ip=request.remote_addr,
                       token=token_value,
                       User_id=user.id,
                       ut_created_at=timestamp,
                       ut_expires_at=expires_at)
         TokenService.clearUserTokens(user.id)
         if database.save_changes(token) is False:
             response.setMessage(
                 "An error occured while persisting data to the database")
         else:
             response.setSuccess()
             response.setMessage("Token successfuly generated")
             response.setDetails({
                 "token": token_value,
                 "expires_at": expires_at
             })
     else:
         response.setMessage("User not found in the database")
     return response
 def updateProfile(user: User, updates: dict):
     response = ApiResponse()
     if user is not None:
         perform_update = False
         old_email = user.email
         if "email" in updates:
             if user.email != updates["email"]:
                 if validate_email(updates["email"]):
                     perform_update = True
                     user.email = updates["email"]
                     user.updated_at = datetime.datetime.utcnow()
                 else:
                     response.setMessage("Invalid e-mail address provided")
         if perform_update:
             if database.save_changes(user) is False:
                 response.setMessage("An error occured while saving user's details")
             else:
                 logger.info("[UserService.updateProfile] {}'s email address changed from '{}' to '{}'".format(
                     user.username,
                     old_email,
                     updates["email"]
                 ))
                 response.setMessage("Email successfuly updated")
                 response.setSuccess()
         if len(response.message) == 0:
             response.setMessage("Nothing was updated")
             response.setSuccess()
     else:
         response.setMessage("Impossible to find your profile")
     return response
Ejemplo n.º 3
0
 def checkToken(token_value: str):
     response = ApiResponse()
     token = TokenService.getValidToken(token_value)
     if token is not None:
         expires_at_dt = datetime.datetime.fromtimestamp(
             token.ut_expires_at)
         response.setSuccess()
         response.setMessage("Valid token until : " + str(expires_at_dt))
         response.setDetails({"expires_at": token.ut_expires_at})
     else:
         response.setMessage("Invalid or expired token, please login")
     return response
Ejemplo n.º 4
0
 def removeToken(token_id: int):
     """
     Renews a token for the maximum expiration time.
     """
     response = ApiResponse()
     Token.query.filter_by(id=token_id).delete()
     if database.save_changes() is False:
         response.setMessage(
             "An error occured while removing the token from the database")
     else:
         response.setSuccess()
         response.setMessage("Token successfuly removed")
     return response
 def getProfile(user: User):
     response = ApiResponse()
     if user is not None:
         response.setSuccess()
         response.setMessage("Details of {} found".format(user.username))
         response.setDetails({
             "ids": user.ids,
             "username": user.username,
             "first_name": user.first_name,
             "last_name": user.last_name,
             "email": user.email,
             "updated_at": user.updated_at
         })
     else:
         response.setMessage("Impossible to find your profile")
     return response
    def updateLDAPUser(user: User):
        """
        Based on user's username.

        Checks for any change in user database details
        from its LDAP details. Updates any change in the
        database.
        """
        response = ApiResponse()
        search_filter = "(&(uid={})(objectClass=inetOrgPerson))".format(user.username)
        try:
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
            connection = ldap.initialize(LDAP_ENDPOINT)
            connection.protocol_version = ldap.VERSION3
            connection.simple_bind_s(LDAP_ADMIN_DN, LDAP_ADMIN_PASSWORD)
            ldap_user = connection.search_s(LDAP_USERS_DN, ldap.SCOPE_SUBTREE, search_filter)
            if len(ldap_user):
                ldap_user_details = {
                    "first_name": ldap_user[0][1]["givenName"][0].decode('utf-8'),
                    "last_name": ldap_user[0][1]["sn"][0].decode('utf-8')
                }
                user_details = {
                    "first_name": user.first_name,
                    "last_name": user.last_name
                }
                response.setSuccess()
                if ldap_user_details != user_details:
                    user.first_name = ldap_user_details["first_name"]
                    user.last_name = ldap_user_details["last_name"]
                    user.updated_at = datetime.datetime.utcnow()
                    if database.save_changes(user) is False:
                        logger.info("User {} was updated from {} to {}".format(
                            user.username,
                            json.dumps(user_details),
                            json.dumps(ldap_user_details)
                        ))
                        response.setError()
                        response.setMessage("An error occured while persisting data to the database")
        except ldap.LDAPError as e:
            logger.debug("[AuthService.updateLDAPUser] Can't perform LDAP search")
            logger.debug(e)
        return response
Ejemplo n.º 7
0
 def renewToken(token_id: int):
     """
     Renews a token for the maximum expiration time.
     """
     response = ApiResponse()
     timestamp = time.time()
     expires_at = int(timestamp + TOKEN_EXPIRATION_TIME)
     token = Token.query.filter_by(id=token_id).first()
     token.ut_expires_at = expires_at
     if database.save_changes(token) is False:
         response.setMessage(
             "An error occured while renewing the token in the database")
     else:
         response.setSuccess()
         response.setMessage("Token successfuly renewed")
         response.setDetails({
             "token": token.token,
             "expires_at": expires_at
         })
     return response