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
示例#2
0
 def get(self, query, limit):
     apiResponse = ApiResponse()
     icons.updateImages()
     icons_found = icons.searchImages(query, limit)
     apiResponse.setError(False if (len(icons_found)) else True)
     apiResponse.setMessage(
         str(len(icons_found)) + " images found for your query" if (
             len(icons_found)) else "No image found for that query")
     apiResponse.setDetails(icons_found)
     return apiResponse.getResponse()
示例#3
0
 def removeToken(token_value: str):
     response = ApiResponse()
     token = Token.query.filter_by(token=token_value).order_by(
         Token.ut_created_at.desc()).first()
     if token is None:
         response.setMessage("Token was not found")
         logger.error("Token was not found. Token: " + token_value)
         return response
     response = TokenService.removeToken(token.id)
     if response.error is False:
         response.setMessage("You've correctly been logged out.")
     return response
示例#4
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
示例#5
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
示例#6
0
    def wrapper(*args, **kwargs):
        response = ApiResponse()
        if "X-Api-Auth-Token" in request.headers:
            token_value = escape(request.headers["X-Api-Auth-Token"])
            response = AuthService.checkToken(token_value)
            if response.error is False:
                response = AuthService.renewToken(token_value)
        else:
            response.setMessage(
                "Missing token in header of the query : X-Api-Auth-Token")

        if response.error is True:
            return response.getResponse()
        else:
            return f(*args, **kwargs)
示例#7
0
 def renewToken(token_value: str):
     response = ApiResponse()
     token = Token.query.filter_by(token=token_value).order_by(
         Token.ut_created_at.desc()).first()
     if token is None:
         response.setMessage("Token was not found")
         logger.error("Token was not found. Token: " + token_value)
         return response
     user = User.query.filter_by(id=token.User_id).first()
     if user is None:
         response.setMessage("No user was found associated with this token")
         logger.error(
             "No user was found associated with this token. Token.id: {}".
             format(token.id))
         return response
     return TokenService.renewToken(token.id)
 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
示例#10
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
 def createUser(user_data):
     """
     Creates a user in the database.
     """
     response = ApiResponse()
     user = User.query.filter_by(username=user_data["username"]).first()
     if not user:
         user = User(
             ids=user_data["ids"],
             username=user_data["username"],
             first_name=user_data["first_name"],
             last_name=user_data["last_name"],
             created_at=user_data["created_at"],
             updated_at=user_data["updated_at"]
         )
         if database.save_changes(user) is False:
             response.setMessage("An error occured while persisting data to the database")
     else:
         response.setMessage("User already exist in the database")
     return response
示例#12
0
    def authLDAPUser(username: str, password: str):
        response = ApiResponse()
        user_details = AuthService.checkLDAPCredentials(username, password)
        if user_details is not False:
            username = user_details[0][1]["uid"][0].decode('utf-8')
            user = User.query.filter_by(username=username).first()

            if user is None:
                # If not yet in database, create user account
                # from users's LDAP details
                sql_datetime = datetime.datetime.utcnow()
                last_id = (UserService.getLastUserID() + 1)
                UserService.createUser({
                    "ids":
                    sha256(hash_id(last_id) + str(time.time())),
                    "username":
                    username,
                    "first_name":
                    user_details[0][1]["givenName"][0].decode('utf-8'),
                    "last_name":
                    user_details[0][1]["sn"][0].decode('utf-8'),
                    "created_at":
                    sql_datetime,
                    "updated_at":
                    sql_datetime
                })
                user = User.query.filter_by(username=username).first()

            if user is not None:
                response = UserService.updateLDAPUser(user)
                if (response.error is False):
                    response = TokenService.generateUserToken(user.id)
                    response.message = response.message if (
                        response.error) else "Authentication succeeded"
            else:
                logger.error("Impossible to find the profile of " + username)
                response.setMessage("Impossible to find your profile")

        else:
            response.setMessage("Invalid username or password")
        return response
示例#13
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