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
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()
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)
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 after_request(response): response.direct_passthrough = False response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,X-Api-Auth-Token') response.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS') response, http_code = ApiResponse.formatFlaskResponse(response) return app.make_response((response, http_code))
def get(self, icon_hash): apiResponse = ApiResponse() icon = icons.getImageData(icon_hash) if (icon): icon.update({"request": icon_hash}) apiResponse.setAll(False, "Image found", icon) else: apiResponse.setAll(True, "Image not found", {"request": icon_hash}) return apiResponse.getResponse()
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 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 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
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
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 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
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
def serialize(self): bg = self.req.bg site = self.req.site plant = self.req.plant startdate = self.req.startdate enddate = self.req.enddate datetime_start = datetime.datetime.fromtimestamp(startdate) datetime_end = datetime.datetime.fromtimestamp(enddate) dtStartStr = datetime_start.strftime('%Y-%m-%d') dtEndStr = datetime_end.strftime('%Y-%m-%d') print(dtStartStr) print(dtEndStr) logger.debug("------DatabaseGetMonthlyPurchaseAmountService Param: ") logger.debug("bg: " + str(bg)) logger.debug("site: " + str(site)) logger.debug("plan: " + str(plant)) logger.debug("score: " + str(dtStartStr) + " ~ " + str(dtEndStr)) queryTyoe = 0 if bg == '' and site == '' and plant == '': queryTyoe = 1 if queryTyoe == 1: sqlquery = 'select mmp_site as site, to_char(po_date , \'YYYY/MM\') as date, sum(po_line_amount) as amount ' \ 'from public."PURCHASE_ORDER" po ' \ 'inner join public."PURCHASE_ORDER_DETAIL" pod ' \ 'on po.po_no = pod.po_no ' \ 'where po_date between \'' + dtStartStr + '\' and \'' + dtEndStr + '\' ' \ 'and charge_plant_code is not null ' \ 'and mmp_bg is not null and mmp_site is not null ' \ 'group by mmp_site, to_char(po_date, \'YYYY/MM\')' \ 'order by mmp_site, to_char(po_date, \'YYYY/MM\')' else: sqlquery = 'select mmp_site as site, to_char(po_date , \'YYYY/MM\') as date, sum(po_line_amount) as amount ' \ 'from public."PURCHASE_ORDER" po ' \ 'inner join public."PURCHASE_ORDER_DETAIL" pod ' \ 'on po.po_no = pod.po_no ' \ 'where po_date between \'' + dtStartStr + '\' and \'' + dtEndStr + '\' ' if plant != '': sqlquery += 'and charge_plant_code in (' + str(plant.split(',')).replace('[','').replace(']','') + ')' if bg != '': sqlquery += 'and mmp_bg in (' + str(bg.split(',')).replace('[', '').replace(']', '') + ')' if site != '': sqlquery += 'and mmp_site in (' + str(site.split(',')).replace('[','').replace(']','') + ')' sqlquery += 'group by mmp_site, to_char(po_date, \'YYYY/MM\') order by mmp_site, to_char(po_date, \'YYYY/MM\')' print(sqlquery) data = GetDataService.getdata(self, sqlquery) if data is None or data == []: return ApiResponse.emitErrorOutput(E_QUERY_FAIL, "查無資料", "no data") result = [] json_result = [] format_string = '' column = ('site', 'date', 'amount') for row in data: result.append(dict(zip(column, row))) old_site = '' for amountdata in result: if old_site != amountdata.get('site') and old_site != '': format_string += '"' + old_site + '":' + str(json_result) + ',' old_site = amountdata.get('site') ammount = str(amountdata.get('amount')) del amountdata['site'] amountdata['amount'] = ammount json_result = [] json_result.append(amountdata) else: old_site = amountdata.get('site') ammount = str(amountdata.get('amount')) del amountdata['site'] amountdata['amount'] = ammount json_result.append(amountdata) format_string += '"' + old_site + '":' + str(json_result) format_string = format_string.replace("\'", "\"") format_string = '{' + format_string + '}' json_data = format_string if json_data is not None: dataJsonArray = json.loads(json_data) result = ApiResponse.emitSuccessOutput(dataJsonArray, msg="get data successfully.") else: result = ApiResponse.emitErrorOutput(E_QUERY_FAIL, "查無資料", "no data") return result
def get(self): apiResponse = ApiResponse() apiResponse.setAll(False, "Everything's up and running", {}) return apiResponse.getResponse()
def get(self): apiResponse = ApiResponse() apiResponse.setAll(False, "Everything's up and running", {"nb_images": len(icons.getImagesData())}) return apiResponse.getResponse()
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
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