def get_image(token): if not utils.verify_token(token): abort(401) image_uuid = utils.verify_token(token) if not utils.check_if_file_exists(image_uuid): abort(404) return send_from_directory(app.config['UPLOAD_FOLDER'], '{}.png'.format(image_uuid), as_attachment=False)
def login(self, *args): credential = verify_token(self.request) if not credential: self.response.write( json.dumps({ 'msg': 'Auth needed', 'login_url': 'http://%s/#/signin' % self.request.host })) self.response.set_status(401) return user_name = credential.get('name', 'Unknown') user_email = credential.get('email', 'Unknown') user = User.get_by_email(user_email) if user is None: user = User() user.name = user_name user.email = [user_email] setup_current_institution(user, self.request) method(self, user, *args)
def rpc_announce_peer(self, sender, args): try: node_id = args["id"] info_hash = args["info_hash"] port = args["port"] token = args["token"] source = Node(node_id, sender[0], sender[1]) self.welcomeIfNewNode(source) self.log.debug("got a store request from %s, storing value" % str(sender)) if verify_token(sender[0], sender[1], token): values = self.storage.get(info_hash, []) values.append((sender[0], port)) # Redeclare value by info_hash self.storage[info_hash] = values return {"y": "r", "r": {"id": self.sourceNode.id}} else: return self._response_error(203, "Protocol Error, bad token") except KeyError: return self._response_error(203, "Protocol Error, invalid arguments")
def verify(): result = utils.verify_token(request, COOKIE_NAME, TOKEN_SECRET) if result: # Verified, fetch user info user_id = result['id'] query = USER.select().where(USER.id == user_id) if query.exists(): # User found, construct json header user = query.dicts().get() auth_header = json.dumps( { 'username': user['username'], 'email': user['email'], } ) # Set header on response resp = make_response(jsonify(success=True)) resp.headers[HEADER_KEY] = auth_header return resp # Not valid, user must login, redirect to login url with correct next-page #Where to? print(request.headers, flush=True) host = request.headers.get('X-Forwarded-Host') uri = request.headers.get('X-Forwarded-Uri', '') return redirect(REDIRECT_URL_ON_FAIL+'?next=http://'+host+uri)
def get(self, token): email = verify_token(token, salt='activate') if email is False: return {'message': 'Invalid token or token expired'}, HTTPStatus.BAD_REQUEST user = User.get_by_email(email=email) if not user: return {'message': 'User not found'}, HTTPStatus.NOT_FOUND if user.is_active is True: return {'message': 'The user account is already activated'}, HTTPStatus.BAD_REQUEST user.is_active = True user.save() return {}, HTTPStatus.NO_CONTENT
def test_bc_password(app, client_nc): # Test behavior of BACKWARDS_COMPAT_AUTH_TOKEN_INVALID response = json_authenticate(client_nc, email="*****@*****.**") token = response.json["response"]["user"]["authentication_token"] verify_token(client_nc, token) json_logout(client_nc, token) with capture_reset_password_requests() as requests: response = client_nc.post( "/reset", json=dict(email="*****@*****.**"), headers={"Content-Type": "application/json"}, ) assert response.status_code == 200 reset_token = requests[0]["token"] data = dict(password="******", password_confirm="awesome sunset") response = client_nc.post( "/reset/" + reset_token + "?include_auth_token=1", json=data, headers={"Content-Type": "application/json"}, ) assert response.status_code == 200 assert "authentication_token" in response.json["response"]["user"] # changing password should have rendered existing auth tokens invalid verify_token(client_nc, token, status=401) # but new auth token should work token = response.json["response"]["user"]["authentication_token"] verify_token(client_nc, token)
def test_bc_password(app, client_nc): # Test behavior of BACKWARDS_COMPAT_AUTH_TOKEN_INVALID response = json_authenticate(client_nc) token = response.json["response"]["user"]["authentication_token"] verify_token(client_nc, token) data = dict( password="******", new_password="******", new_password_confirm="new strong password", ) response = client_nc.post( "/change?include_auth_token=1", json=data, headers={"Content-Type": "application/json", "Authentication-Token": token}, ) assert response.status_code == 200 assert "authentication_token" in response.json["response"]["user"] # changing password should have rendered existing auth tokens invalid verify_token(client_nc, token, status=401) # but new auth token should work token = response.json["response"]["user"]["authentication_token"] verify_token(client_nc, token)
def get(self, token): email = verify_token(token, salt="activate") if email is False: return ( {"message": "invalid token or token expired."}, HTTPStatus.BAD_REQUEST, ) user = User.get_by_email(email=email) if not user: return {"message": "User not found."} if user.is_active is True: return ( {"message": "The user account is alredy activated."}, HTTPStatus.BAD_REQUEST, ) user.is_active = True user.save() return {}, HTTPStatus.NO_CONTENT
def get(self, token): """This method has the logic to verify the token, email and the user account status""" email = verify_token(token, salt='activate') if email is False: return {'message': 'Invalid token or token expired'}, HTTPStatus.BAD_REQUEST user = User.get_by_email(email=email) if not user: return {'message': 'User not found'}, HTTPStatus.NOT_FOUND # If the user account is already activated if user.is_active is True: return {'message': 'The user account is already activated'}, HTTPStatus.BAD_REQUEST user.is_active = True user.save() # Request was handled successfully return {}, HTTPStatus.NO_CONTENT
def test_change_uniquifier(app, client_nc): # make sure that existing token no longer works once we change the uniquifier response = json_authenticate(client_nc) token = response.json["response"]["user"]["authentication_token"] verify_token(client_nc, token) # now change uniquifier with app.test_request_context("/"): user = app.security.datastore.find_user(email="*****@*****.**") app.security.datastore.reset_user_access(user) app.security.datastore.commit() verify_token(client_nc, token, status=401) # get new token and verify it works response = json_authenticate(client_nc) token = response.json["response"]["user"]["authentication_token"] verify_token(client_nc, token)
def logout(token: str): token_exists = utils.verify_token(token = token) if not token_exists: raise HTTPException(status_code = 400, detail = 'Token is not available') return utils.logout(token)
def delete_secret(secret: schemas.forDeleteSecret): token_exists = utils.verify_token(token = secret.token) if not token_exists: raise HTTPException(status_code = 400, detail = 'Token is not available') return utils.delete_secret(secret)
def update_password(user: schemas.forUpdatePassword): token_exists = utils.verify_token(token = user.token) if not token_exists: raise HTTPException(status_code = 400, detail = 'Token is not available') return utils.update_password(user)
def get(self): parse = reqparse.RequestParser() parse.add_argument('id', type=int, help='错误的id', default='0') parse.add_argument('width', type=int, help='wrong width', default=300) parse.add_argument('height', type=int, help='wrong height', default=300) parse.add_argument('token', type=str, help='wrong token') args = parse.parse_args() # 获取当前文件夹id file_id = args.get('id') width = args.get('width') height = args.get('height') token = args.get('token') try: user = verify_token(token) except: response = make_response(jsonify(code=38, message='wrong token')) return response try: file_node = FileNode.query.get(file_id) except: response = make_response( jsonify(code=11, message='node not exist, query fail')) return response if file_node.user_id != user.uid: response = make_response(jsonify(code=38, message='wrong token')) return response if file_node == None: response = make_response( jsonify(code=11, message='node not exist, query fail')) return response if file_node.type_of_node in config['IMG_TYPE']: parent_id = file_node.parent_id filename = file_node.filename node_type = file_node.type_of_node # 生成文件名的 hash actual_filename = generate_file_name(parent_id, filename) # 结合 UPLOAD_FOLDER 得到最终文件的存储路径 target_file = os.path.join(os.path.expanduser(UPLOAD_FOLDER), actual_filename) if os.path.exists(target_file): try: with Image.open(target_file, mode='r') as img_data: # img_data = Image.open(target_file) img_data.thumbnail((width, height)) fp = io.BytesIO() format = Image.registered_extensions()['.' + node_type] img_data.save(fp, format) response = make_response(fp.getvalue()) response.headers['Content-Type'] = 'image/' + node_type return response except: response = make_response( jsonify(code=24, message='preview not allowed')) return response else: response = make_response( jsonify(code=22, message='file not exist')) return response else: response = make_response( jsonify(code=24, message='preview not allowed')) return response