def setUp(self): self.auth = Auth() with SensitiveData() as sd: app_id = sd.get('app_id_l1') app_key = sd.get('app_key_l1') self.auth.init(app_id, app_key)
def verify_token(*args, **kwargs): auth = Auth() try: result = auth.verify_auth_token(request.args.get('token')) if result['status'] == 200: return f(*args, **kwargs) else: abort(result['status'], result['message']) except KeyError as e: abort(401, 'Você precisa enviar um token de acesso')
def doLogin(): if (request.form['username'] == config['username'] and request.form['password'] == config['password']): auth = Auth() data = {'username': config['username'], 'senha': config['password']} response = { 'access_token': auth.generate_auth_token(data).decode('utf-8'), 'token_type': "JWT" } return Response(json.dumps(response, ensure_ascii=False), mimetype='application/json'), 200 else: abort(401, 'Dados não encontrados')
def get_user(): from flask import request from users.models import Users from utils.auth import Auth is_vaild, info = Auth.decode_auth_token(request.headers['jwt']) user = Users.query.filter_by(id=info["id"]).first() return user
def post(self): # TODO: validate parameters args = request.get_json(force=True, silent=True) token_validation = Auth.auth_token(request.headers) if (token_validation != 'True'): return token_validation if args is None: return False, 500 event_data = args try: user = User_model.objects.get(uuid=args['creator_uuid']) except DoesNotExist: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load(errorCodes)['USER_ERROR']['NOT_FOUND'], 500 new_event = Event_model(event_date=int(event_data['event_date']), title=event_data['title'], description=event_data['description'], court_id=event_data['court_id'], creator=user['id'], sport=event_data['sport_id']['$oid'], participants=[user['id']]) try: new_event.save() except ValidationError: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load(errorCodes)['EVENT_ERROR']['NOT_VALID'], 500 event = new_event.to_json() return eval(dumps(event)), 200
def post(self): # pylint: disable=E1101 args = request.get_json(force=True, silent=True)['params'] headers = request.headers token_validation = Auth.auth_token(headers) if (token_validation != 'True'): return token_validation try: event = Event_model.objects.get(id=ObjectId(args['eventID'])) except DoesNotExist: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load(errorCodes)['EVENT_ERROR']['NOT_FOUND'], 500 photo_url = args['photoURL'] found = False for url in event['photos']: if url == photo_url: found = True event.update(pull__photos=photo_url) break if not found: event.photos.append(photo_url) try: event.save() except ValidationError: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load( errorCodes)['EVENT_ERROR']['NOT_VALID'], 500 return eval(dumps(event)), 200 return photo_url, 200
def get(self, id): headers = request.headers token_validation = Auth.auth_token(headers) if (token_validation != 'True'): return token_validation query = [] args = request.args sportID = args.get('sport-id') if sportID is not None: query.append({"$match": {"_id": ObjectId(sportID)}}) sports_data = Sport_model.objects.aggregate(*query) sports_json = eval(dumps(sports_data))[0] resource_url = sports_json['resource_url'] response = requests.get(resource_url) data = response.json() data = data['features'] for feature in data: record = feature['properties'] record['INFOESP'] = record['INFOESP'][0] record.pop('PRECIOS', None) record.pop('HORARIOS', None) record.pop('DESCRIPCION', None) record.pop('CONTACTO', None) if id is not None: if int(id) == record['ID']: return [feature], 200 return data, 200
def post(self): data = request.values if data["username"]: if Users.query.filter_by(username=data["username"]).first(): return falseReturn("用户已存在") else: user = Users(username=data["username"], password=Users.set_password( Users, data["password"])) db.session.add(user) db.session.commit() if user.id: return Auth.authenticate(Auth, data["username"], data["password"]) else: return falseReturn("注册失败") # if verify(data): # user = Users( # username=data["username"], # password=Users.set_password(Users, data["password"]) # ) # db.session.add(user) # db.session.commit() # if user.id: # return Auth.authenticate(Auth, data["username"], data["password"]) # else: # return falseReturn("注册失败") # else: # return falseReturn("验证码错误") else: return falseReturn("请输入用户名")
def put(self, id): # pylint: disable=E1101 args = request.get_json(force=True, silent=True)['params'] headers = request.headers token_validation = Auth.auth_token(headers) event = None if (token_validation != 'True'): return token_validation try: event = Event_model.objects.get(id=id) except DoesNotExist: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load(errorCodes)['EVENT_ERROR']['NOT_FOUND'], 500 if args['participantUUID'] is None: try: if args['eventDate'] is not None: event.event_date = args['eventDate'] if args['title'] is not None: event.title = args['title'] if args['description'] is not None: event.description = args['description'] try: event.save() except ValidationError: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load( errorCodes)['EVENT_ERROR']['NOT_VALID'], 500 except DoesNotExist: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load( errorCodes)['EVENT_ERROR']['NOT_FOUND'], 500 if args['participantUUID'] is not None: try: participant = User_model.objects.get( uuid=args['participantUUID']) except DoesNotExist: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load( errorCodes)['USER_ERROR']['NOT_FOUND'], 500 found = False for p in event['participants']: if p.id == participant.id: found = True event.update(pull__participants=participant.id) break if not found: event.participants.append(ObjectId(participant.id)) try: event.save() except ValidationError: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load( errorCodes)['EVENT_ERROR']['NOT_VALID'], 500 return eval(dumps(event)), 200 return 200
class DBInsertStopData(unittest.TestCase): def setUp(self): self.auth = Auth() with SensitiveData() as sd: app_id = sd.get('app_id_l1') app_key = sd.get('app_key_l1') self.auth.init(app_id, app_key) def test_insert_stop(self): conf = configuration.copy() with utils.db_access.BusStopData() as bsd: bsd.drop_data() while True: response = request('get', get_session_url(bus_stop_resource, conf), headers=self.auth.get_auth_header()) conf['data_start_point'] += conf['data_per_session'] if response.content.__len__() < 5: break content = response.content.decode('utf8') stops = json.loads(content) for stop in stops: bsd.write_entry(stop) print('Current pass : {}'.format(conf['data_start_point'])) def test_insert_station(self): conf = configuration.copy() with utils.db_access.BusStationData() as bsd: bsd.drop_data() while True: response = request('get', get_session_url(bus_station_resource, conf), headers=self.auth.get_auth_header()) conf['data_start_point'] += conf['data_per_session'] if response.content.__len__() < 5: break content = response.content.decode('utf8') stops = json.loads(content) for stop in stops: bsd.write_entry(stop) print('Current pass : {}'.format(conf['data_start_point']))
def post(self): data = request.values username = data["username"] password = data["password"] if not username or not password: return falseReturn("用户名和密码不能为空") else: return Auth.authenticate(Auth, username, password)
def post(self): from utils.auth import Auth data = request.values token = data.get("token") auth, info = Auth().decode_auth_token(token) if auth: return trueReturn(info) else: return falseReturn(info)
def wrapper(self, *args, **kwargs): from flask import request from utils.auth import Auth is_vaild, info = Auth.decode_auth_token(request.headers['jwt']) if info["is_super"]: fn = origin_func(self, *args, **kwargs) return fn else: return falseReturn("无权访问")
def get_profile(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: return json.dumps({"error_message": err}), status error_message, status, response = MemberController.get_profile( fam_id, member_id) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": response}), status
def resend_verification(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err and err != 'Not a verified member': return json.dumps({"error_message": err}), status error_message, status = VerificationController.resend_verification( member_id) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": "Success!"}), status
def get_cart(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: return json.dumps({"error_message": err}), 400 error_message, status, response = ListToCartController.get_cart(fam_id) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({ "response": list(map(lambda x: x.json() if x else None, response)) }), status
def check_auth_token(handler): authorization = handler.headers.get("Authorization") if not authorization: return False authorization = authorization.split(" ") if authorization[0] != "Bearer": return False session = OauthSession.query( OauthSession.auth_token == authorization[1]).get() if not session: return False acct = get_account_by_id(get_server_auth(), session.account_id) handler.auth = Auth(acct) return True
def delete(self, id): # pylint: disable=E1101 headers = request.headers token_validation = Auth.auth_token(headers) if (token_validation != 'True'): return token_validation try: Comment_model.objects.get(id=ObjectId(id)).delete() except DoesNotExist: with open('utils/errorCodes.json', 'r') as errorCodes: return json.load(errorCodes)['COMMENT_ERROR']['NOT_FOUND'], 500 return True, 200
def wrapper(self, *args, **kwargs): from flask import request from utils.auth import Auth # 请求头是否包含"jwt" if "jwt" in request.headers: is_vaild, info = Auth.decode_auth_token(request.headers['jwt']) if is_vaild: fn = origin_func(self, *args, **kwargs) return fn else: return falseReturn(info) else: return VaildReturn("")
def verify_member(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err and err != 'Not a verified member': return json.dumps({"error_message": err}), status data = json.loads(request.data.decode('utf-8')) req_params = ["verification_code"] if not ReqParser.check_body(data, req_params): return json.dumps({"error_message": "ill-formed request"}), 400 error_message, status = VerificationController.verify_member( data['verification_code'], member_id) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": "Success!"}), status
def invite_by_email(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: return json.dumps({"error_message": err}), 400 data = json.loads(request.data.decode('utf-8')) req_params = ['admin', 'member'] if not ReqParser.check_body(data, req_params): return json.dumps({"error_message": "ill-formed request"}) error_message, status = FamilyController.invite_by_email(data['admin'], data['member'], fam_id) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": "Success"}), status
def register_family(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err and err != 'Not registered to family': return json.dumps({"error_message": err}), 400 data = json.loads(request.data.decode('utf-8')) req_params = ['address_line1', 'address_line2', 'city', 'state', 'zip_code', 'name'] if not ReqParser.check_body(data, req_params): return json.dumps({"error_message": "ill-formed request"}), 400 error_message, status, response = FamilyController.register_family(data, member_id) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": response}), status
def signin_by_token(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: if member_id == 0: return json.dumps({"error_message": err}), status else: return json.dumps({"response": err}), 200 auth_header = request.headers.get('Authorization') error_message, status, token = MemberController.update_token( auth_header.split(" ")[1]) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": token, "uid": member_id}), status
def checkout(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: return json.dumps({"error_message": err}), status data = json.loads(request.data.decode('utf-8')) req_params = ['total', 'items'] if not ReqParser.check_body(data, req_params): return json.dumps({"error_message": "ill-formed request"}), 400 error_message, status = CheckoutController.checkout( member_id, fam_id, data['total'], data['items']) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": "Success!"}), 200
def register_list_to_cart(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: return json.dumps({"error_message": err}), 400 data = json.loads(request.data.decode('utf-8')) req_params = ["alias", "in_store"] if not ReqParser.check_body(data, req_params): return json.dumps({"error_message": "ill-formed request"}), 400 error_message, status = ListToCartController.register_list( member_id, fam_id, data['alias'], data['in_store']) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": "Success!"}), status
def get(self): # pylint: disable=E1101 headers = request.headers token_validation = Auth.auth_token(headers) if (token_validation != 'True'): return token_validation result = [] args = request.args lat = args.get('lat') lon = args.get('lon') transports_data = Transport_model.objects for transport in transports_data: resource_url = transport['resource_url'] response = requests.get(resource_url) data = response.json() data = data['features'] if lat is not None and lon is not None: currentData = [] for feature in data: record = feature['properties'] record.pop('timestamp', None) record.pop('begin', None) record.pop('end', None) record.pop('altitudemode', None) record.pop('tessellate', None) record.pop('extrude', None) record.pop('visibility', None) record.pop('draworder', None) record.pop('icon', None) record['marker_url'] = transport.marker_url flat = float(feature['geometry']['coordinates'][0]) flon = float(feature['geometry']['coordinates'][1]) distance = Distance.calc_distance(lat, lon, flat, flon) if distance >= 0 and distance <= 1: currentData.append(feature) result.append({ "type": transport.name, "data": currentData, "marker_url": transport.marker_url }) return result, 200
def delete_cart(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: return json.dumps({"error_message": err}), 400 data = json.loads(request.data.decode('utf-8')) req_params = ["victim_ids"] if not ReqParser.check_body(data, req_params): return json.dumps({"error_message": "ill-formed request"}), 400 error_message, status, response = ListToCartController.delete_cart( fam_id, data['victim_ids']) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({ "response": list(map(lambda x: x.json() if x else None, response)) }), status
def edit_niche(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: return json.dumps({"error_message": err}), 400 data = json.loads(request.data.decode('utf-8')) req_params = [ 'device_id', 'alert_level', 'container', 'alias', 'auto_order_store', 'product_metadata' ] if not ReqParser.check_body(data, req_params): return json.dumps({"error_message": "ill-formed request"}), 400 error_message, status = DeviceDataController.edit_niche(fam_id, data) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": "Success"}), status
def change_shadow_fam(cls): """ allow other users to change when this scenario becomes common """ err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: return json.dumps({"error_message": err}), status data = json.loads(request.data.decode('utf-8')) req_params = ['secret', 'device_id'] if not ReqParser.check_body(data, req_params): return json.dumps({"error_message": "ill-formed request"}), 400 error_message, status = DeviceDataController.change_shadow_fam( fam_id, data) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": "Success"}), status
def edit_list_to_cart(cls): err, status, member_id, fam_id = Auth.whoisit(request.headers) if err: return json.dumps({"error_message": err}), 400 data = json.loads(request.data.decode('utf-8')) req_params = [ "alias", "in_cart", "in_store", "item_name", "item_image", "item_price", "item_quantity", "list_to_cart_id" ] if not ReqParser.check_body(data, req_params): return json.dumps({"error_message": "ill-formed request"}), 400 error_message, status = ListToCartController.edit_list_to_cart( fam_id, data) if error_message: return json.dumps({"error_message": error_message}), status return json.dumps({"response": "Success"}), status