def post(): if request.json: json = request.json user = UserService.get_bu_username(json['username']) if not user or not user.check_password(json['password']): return "no authentication", 401 jwt_token = create_access_token(identity=user.uuid, expires_delta=timedelta(hours=2)) return {"jwt_token": "Bearer " + jwt_token}, 200 else: if not request.form.get('password') or not request.form.get( 'username'): return "wrong input", 401 user = UserService.get_bu_username(request.form.get('username')) if not user or not user.check_password( request.form.get('password')): return redirect(url_for('mainpage')) jwt_token = create_access_token(identity=user.uuid, expires_delta=timedelta(hours=2)) login_user(user) headers = {'jwt_token': jwt_token} resp = make_response(redirect(url_for('personal')), 302, headers) r = redirect(url_for('personal')) set_access_cookies(resp, jwt_token) return resp
def update(cls, mysql, user_id): service = UserService(mysql) try: user = service.update(user_id) except ResourceNotFoundException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 404 except MissingFieldException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 400 except ResourceAlreadyExistsException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 400 repo = UserRepository(mysql) user = repo.update(user) return cls.get_by_filter(mysql, 'id', user.get_id())
def test_login_no_email_or_password(self): user = UserModel(user_schema.load(self.user1)) user.save() res = UserService.login( user_schema.load({'email': '*****@*****.**'}, partial=True)) self.assertEqual(res.status_code, 400) res = UserService.login( user_schema.load({'password': '******'}, partial=True)) self.assertEqual(res.status_code, 400)
def test_get_user_data(self): mock_dao = Mock() email = '*****@*****.**' name = 'some name' mock_dao.get_all.return_value = User(email, name) service = UserService(mock_dao) user = service.get_user(email) self.assertEqual(user.get_email(), email) self.assertEqual(user.get_name(), name)
def test_user_create_user_with_same_mail(self): user = UserModel(user_schema.load(self.user1)) user.save() res = UserService.create(user_schema.load(self.user1)) self.assertEqual(res.status_code, 400)
def post(self): try: home = self.homes_schema.load(request.json, session=db.session) except ValidationError as e: return {"message": str(e)}, 400 response_home_added = home.add(UserService.get_current_user()) return self.homes_schema.dump(response_home_added), 201
def test_login_wrong_password(self): user = UserModel(user_schema.load(self.user1)) user.save() wrong_password = { 'email': '*****@*****.**', 'password': '******' } res = UserService.login(user_schema.load(wrong_password, partial=True)) self.assertEqual(res.status_code, 400)
def test_user_update(self): user = UserModel(user_schema.load(self.user1)) user.save() res = UserService.update( user_schema.load({'name': 'test'}, partial=True)) json_data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(json_data.get('name'), 'test')
def authenticate(cls, mysql): user_service = UserService(mysql) try: user = user_service.authenticate() except MissingFieldException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 400 except InvalidInput as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 400 except MissingHeaderException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 400 except ResourceNotFoundException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 403 except InvalidCredentialsException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 403 except InactiveUserException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 403 return jsonify({ 'id': user.get_id(), 'email': user.get_email(), 'username': user.get_user_name(), 'active': user.get_is_active(), 'token': user.get_token() }), 200
def create(cls, mysql): service = UserService(mysql) try: user = service.validate_payload_for_creation_and_hydrate() except MissingFieldException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 400 except ResourceAlreadyExistsException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 400 user = service.create(user) return cls.get_by_filter(mysql, 'id', user.get_id())
def post(self): if request.json: try: user = self.user_schema.load(request.json, session=db.session) print(user) return UserService.add(user) except ValidationError as e: return {"message": str(e)}, 400 else: try: user = self.user_schema.load( { "username": request.form.get('username'), "password": request.form.get('password'), "email": request.form.get('email') }, session=db.session) except ValidationError as e: return {"message": str(e)}, 400 UserService.add(user) return redirect(url_for("mainpage"))
def get_by_filter(cls, mysql, filter, filter_value): user_service = UserService(mysql) try: user = user_service.get_by_filter(filter, filter_value) except UnsupportedFilterException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 400 except ResourceNotFoundException as error: return jsonify({ 'message': str(error), 'code': error.get_code() }), 404 return jsonify({ 'id': user.get_id(), 'email': user.get_email(), 'username': user.get_user_name(), 'active': user.get_is_active() }), 200
def test_delete_user(self): user = UserModel(user_schema.load(self.user1)) user.save() res = UserService.delete() self.assertEqual(res.status_code, 204)
def post(self): """Login User""" return UserService.login(request.parsed_obj)
def get(self): """Get logged in user""" return UserService.get_logged_in_user()
def delete(self): """Delete current User""" return UserService.delete()
def put(self): """Update user""" return UserService.update(request.parsed_obj)
from flask import Blueprint, request from flask_cors import cross_origin, CORS from src.API.utils import objects_to_json from src.service.user_service import UserService user_api = Blueprint('user_api', __name__) CORS(user_api, suppport_credentials=True) service = UserService() @user_api.route('/userData', methods=['GET']) @cross_origin(support_credentials=True) def user_data(): email = request.args.get('userEmail') return {'user': objects_to_json(service.get_user(email))}
SESSION_ID = "my-session-id" ACCESS_TOKEN = "access-token" ACCESS_TOKEN_COOKIE = "access_token_cookie" TOKEN_EXPIRES_IN_SECONDS = 300 app.config['JWT_SECRET_KEY'] = os.environ.get(SECRET_KEY) app.secret_key = os.environ.get(SECRET_KEY) app.config['JWT_ACCESS_TOKEN_EXPIRES'] = TOKEN_EXPIRES_IN_SECONDS app.config['JWT_TOKEN_LOCATION'] = ('headers', 'cookies') app.config['JWT_COOKIE_SECURE'] = True app.config['JWT_COOKIE_CSRF_PROTECT'] = False jwt = JWTManager(app) user_service = UserService() note_service = NoteService() validator = Validator() @jwt.unauthorized_loader def my_unauthorized_loader_function(callback): return render_template("errors/403.html"), 403 @app.route('/') def index(): return render_template('index.html') # ==================================== LOGIN ======================================
def test_login(self): user = UserModel(user_schema.load(self.user1)) user.save() partial_user = {'email': '*****@*****.**', 'password': '******'} res = UserService.login(user_schema.load(partial_user, partial=True)) self.assertEqual(res.status_code, 200)
def test_user_create(self): res = UserService.create(user_schema.load(self.user1)) self.assertEqual(res.status_code, 201)
def renew_token(cls, mysql, current_user): user_service = UserService(mysql) user_service.renew_token(current_user) return cls.get_by_filter(mysql, 'id', current_user.get_id())
class LoginPage: def __init__(self): self.user_service = UserService() self.permission_service = Permission() def login_page(self): for i in range(3): intent = input("请选择登录or注册-->1:登录 2:注册") if intent.isdigit() and intent in ('1', '2'): intent = int(intent) if intent == 1: '''调登录方法''' for j in range(3): if j == 2: '''tag决定数据库连接什么时候关闭''' tag = 1 else: tag = 0 result = self.enter_login(tag) '''表示登录成功''' if result['code'] == 200: '''跳转到下一个页面,把基本信息带入''' self.home_page(result['data']['user_info']) return elif result['code'] == 202: if j == 2: print("错误次数太多了,明天再来") return else: print(result['data']['msg'], '请重新输入') else: print("服务器异常:", result['data']['Exception']) return pass if intent == 2: pass else: if i == 2: print("错误次数太多了,明天再来") return else: print("输入错误,请重新输入") def enter_login(self, tag): username = input("username:"******"password") return self.user_service.login(username, password, tag) def home_page(self, args): print('欢迎你%s,告诉我您要做什么' % args['full_name']) '''获取所有权限''' role_dict = self.permission_service.get_permission(args['role_id']) print(role_dict) number_list = [] for i, v in enumerate(role_dict, 1): print(i, v['caption']) number_list.append(str(i)) for i in range(3): number = input("请输入编号:") '''表示输入非法''' if number.isdigit() is False or number not in number_list: if i == 2: print('输入错误次数太多了') return else: print('输入非法,请重新输入') else: '''动态找到需要调用的方法,这里如果方法路径不是当前路径可以用importlib动态导入模块''' fun_name = role_dict[int(number) - 1]['fun'] '''反射的方式调用方法''' getattr(self, fun_name)(args) def modify_password_page(self, args): old_password = input('请输入老密码:') new_password = input("请输入新密码:") response = self.user_service.modify_password(args['username'], old_password, new_password) print(response)
def get(self, uuid=None): if not uuid: return self.homes_schema.dump(Home.get_all( UserService.get_current_user()), many=True), 200 return self.homes_schema.dump(Home.get_by_uuid(uuid)), 200
def post(self): """Register""" return UserService.create(request.parsed_obj)
def __init__(self, user_service=UserService()): self.dao = ConsortiumDAO() self.user_service = user_service self.email_service = EmailService()
def __init__(self): self.user_service = UserService() self.permission_service = Permission()