def login(): profile = request.get_json(force=True)['profile'] unique_id = profile['googleId'] users_email = profile['email'] picture = profile['imageUrl'] users_name = profile['name'] current_app.user_uid = unique_id session['user_uid'] = unique_id # Create a user in your db with the information provided # by Google user = User(id_=unique_id, name=users_name, email=users_email, avatar=picture) new_user = False # Remember to change back! # Doesn't exist? Add it to the database. if not User.get(unique_id): new_user = True print("User doesn't exist, creating new User") User.create(unique_id, users_name, users_email, picture) # Begin user session by logging the user in (using Flask Log-in) login_user(user) return jsonify(message=current_user.is_authenticated, new_user=new_user), 200
def createUser(): if (request.method == 'POST'): arg_param = request.get_json() # Se verifica si los parametros existen _arg_email = verifyExist(arg_param, 'email') _arg_password = verifyExist(arg_param, 'password') data_obligatorios = [_arg_email, _arg_password] verify_obligatorios = verifyRequired(data_obligatorios) if (verify_obligatorios == False): return jsonify(response_incomplete), 401 # Se llama la clase que tiene el metodo de creacion de usuario __user = User(_arg_email, _arg_password) r_create = __user.createUser() r_status = 200 if (r_create == False): r_create = response_false r_status = 401 return jsonify(r_create), r_status
class TestChangeUserInfo(unittest.TestCase): user = User() service = Service() service_model = service_settings['change_user_info'] @classmethod def setUpClass(cls): """创建普通用户和管理员用户""" cls.assertTrue(cls(), cls.user.login_super_admin()) @classmethod def tearDownClass(cls): """删除创建用户,执行清理操作""" pass def setUp(self): """每个测试用例开始执行拷贝一份之前构造好的post data""" pass def tearDown(self): """每个测试用例结束之后恢复post data""" pass @skip('接口变换,此用例暂时不执行') @data({'newPw': '12345678', 'oldPw': '12345678'}, unpack=False) def test_step_one(self, json_data): """用户修改密码""" # 用户登陆退出 response = self.service.change_password(output=True, json_data=json_data) self.assertEqual(response.status, codes.SUCCESSFUL_OPERATION)
class TestChangeUserInfo(unittest.TestCase): user = User() system_init = SystemInit() @classmethod def setUpClass(cls): """超级管理员登陆""" cls.assertTrue(cls(), cls.user.login_super_admin().check) @classmethod def tearDownClass(cls): """""" pass def setUp(self): """""" pass def tearDown(self): """""" pass def test_step_one(self): """""" self.assertTrue( self.system_init.check_system_initial_state(output=True).check)
class TestInitRootOrg(unittest.TestCase): """ 初始化根组织机构 """ user = User() system_init = SystemInit() @classmethod def setUpClass(cls): """超级管理员登陆""" cls.assertTrue(cls(), cls.user.login_super_admin().check) @classmethod def tearDownClass(cls): """""" pass def setUp(self): """""" pass def tearDown(self): """""" pass @data(123, 'test', '') def test_step_one(self, name): """初始化根节点接口成功""" json_data = { 'rootOrgName':name } self.assertTrue(self.system_init.check_system_initial_state(output=True).check) self.assertTrue(self.system_init.init_root_org(json_data=json_data, output=True).check)
def user(): user = User({ 'token': 'some-awesome-apikey', 'env': 'test', 'user': '******' }) return user
class TestChangeUserInfo(unittest.TestCase): user = User() service = Service() service_model = service_settings['change_user_info'] @classmethod def setUpClass(cls): """创建普通用户和管理员用户""" pass @classmethod def tearDownClass(cls): """删除创建用户,执行清理操作""" pass def setUp(self): """每个测试用例开始执行拷贝一份之前构造好的post data""" pass def tearDown(self): """每个测试用例结束之后恢复post data""" pass def test_step_one(self): """用户未登陆情况下查询用户状态""" # 用户登陆退出 self.user.logout_user() response = self.service.get_login_mode_for_current_user( output=True).to_json() self.assertEqual(response.status, codes.SESSION_USER_NOT_FOUND)
def map_model_to_user(model: models.User) -> User: user = User(oid=model.id, username=model.username, full_name=model.full_name, email=model.email, disabled=model.disabled, password=model.hashed_password) return user
def __init__(self, **kwargs): self.id = kwargs.get('id') self.token_type = kwargs.get('token_type') self.access_token = kwargs.get('access_token') self.refresh_token = kwargs.get('refresh_token') self.client_id = kwargs.get('client_id') self.expires = kwargs.get('expires') self.user = User.get_by_id(kwargs.get('user_id')) if kwargs.get('user') is None else kwargs.get('user') self.scope = self.get_scope_string(**kwargs)
async def create_user(user: User) -> models.User: with session_scope() as s: # s.expire_on_commit = False user_db = map_user_to_model(user) user_db.hashed_password = pwd_context.hash(user.password) s.add(user_db) s.flush() user.oid = user_db.id return user
def __init__(self, **kwargs): self.id = kwargs.get('id') self.token_type = kwargs.get('token_type') self.access_token = kwargs.get('access_token') self.refresh_token = kwargs.get('refresh_token') self.client_id = kwargs.get('client_id') self.expires = kwargs.get('expires') self.user = User.get_by_id(kwargs.get( 'user_id')) if kwargs.get('user') is None else kwargs.get('user') self.scope = self.get_scope_string(**kwargs)
class TestCheckSystemInitialState(unittest.TestCase): user = User() service = Service() system_init = SystemInit() @classmethod def setUpClass(cls): """超级管理员登陆""" cls.assertTrue(cls(), cls.user.login_super_admin().check) # cls.service.change_password() @classmethod def tearDownClass(cls): """""" pass def setUp(self): """""" pass def tearDown(self): """""" pass def test_step_one(self): """设备恢复出厂设置,判断设备的初始化状态为未初始化""" if init_device(): ret = self.system_init.check_system_initial_state(output=True) self.assertTrue(ret.check) self.assertEqual(ret.response.inited, inited.uninitialized.value) else: self.fail('设备初始化失败') def test_step_two(self): """初始化系统,判断设备的初始化状态为初始化""" # 初始化系统 if init_device(): self.assertTrue(self.user.login_super_admin().check) ret = self.system_init.check_system_initial_state(output=True) self.assertTrue(ret.check) self.assertEqual(ret.response.inited, inited.uninitialized.value) else: self.fail('设备初始化失败')
class AppTest(unittest.TestCase): def setUp(self): with open("settings.json") as f: data = json.load(f) self.TOKEN = data['TOKEN'] self.user = User(user_id=0000, fields=[]) def test_get_params(self): add_params = {'sex': 1} res = self.user.get_params(add_params) self.assertEqual(res, { 'access_token': self.TOKEN, 'v': version, 'sex': 1 }) def test_check_age(self): age = '20-128' age = check_age(age) self.assertEqual(age, [20, 120])
def user(self): return User(auth=self.auth)
def permission_ok(method, path): user = User(cookie_info.uid.decode('utf8')) logging.debug(user) return True
def setUp(self): with open("settings.json") as f: data = json.load(f) self.TOKEN = data['TOKEN'] self.user = User(user_id=0000, fields=[])
def load_user(user_id): return User.get(user_id)
class TestChangeUserInfo(unittest.TestCase): user = User() service = Service() service_model = service_settings['change_user_info'] @classmethod def setUpClass(cls): """ step 1 管理员登陆,assert超级管理员务必登陆成功否则后续不必执行,获取接口返回的uid step 2 调用用户查询接口,获取该uid对应的详细账号信息 step 3 将获取的账号信息转换成change user info接口调用的元数据 """ system = SystemInit() inited = system_init.check_system_initial_state.inited self = cls() ret = cls.user.login_super_admin() cls.assertTrue(self, ret.check, '超级管理员登陆失败,请检查配置') sys_ret = system.check_system_initial_state() cls.assertTrue(self, sys_ret.check) cls.assertEqual(self, sys_ret.response.inited, inited.initialized.value, '设备没有初始化,请初始化') cls.meta_user_info = make_user_info(ret.response.result) @classmethod def tearDownClass(cls): """删除创建用户,执行清理操作""" self = cls() ret = cls.user.login_super_admin() cls.assertTrue(self, ret.check, '超级管理员登陆失败,请检查配置') ret = cls.service.change_user_info(cls.meta_user_info) cls.assertTrue(self, ret.check, '恢复修改超级管理员默认信息失败,请检查接口') def setUp(self): """每个测试用例开始执行拷贝一份之前构造好的post data""" self.json_data = deepcopy(self.meta_user_info) def tearDown(self): """每个测试用例结束之后恢复post data""" self.json_data = deepcopy(self.meta_user_info) @data('Ywh123456', '!@#!@#!@#!@#!@#', '123', '111111111111111111111111111111', '12345678', '111111111111111111111111111111111111111111111111111111111') def test_step_001(self, new_password): """超级管理员用户修改密码-->修改成长度超过30的密码接口返回信息依旧是密码长度应该大于等于8位""" self.json_data['newPw'] = new_password pwd_length = len(new_password) if 8 <= pwd_length <= 30: ret = self.service.change_user_info(self.json_data, output=True) self.assertTrue(ret.check, '超级管理员修改密码失败') elif 0 < pwd_length < 8: ret = self.service.change_user_info( self.json_data, output=True, expect=codes.PASSWORD_LENGTH_SHOULD_GREATER_THEN_EIGHT) self.assertTrue(ret.check) else: # 此处为后端接口的问题,接口应该新建一个状态码表示密码长度超长,不过前端页面做了限制,此处可以忽略 ret = self.service.change_user_info( self.json_data, output=True, expect=codes.PASSWORD_LENGTH_SHOULD_GREATER_THEN_EIGHT) self.assertTrue(ret.check, '超级管理员修改密码失败') @data({ 'phone': '13132131231', 'code': 1232 }, { 'phone': '13132131232', 'code': '123123' }, { 'phone': '131321311232', 'code': '' }) def test_step_002(self, **kwargs): """超级管理员用户修改手机号,验证码为空或者错误验证码""" for k, v in kwargs.items(): self.json_data[k] = v ret = self.service.change_user_info( self.json_data, output=True, expect=codes.SMS_VERIFICATION_CODE_ERROR) self.assertTrue(ret.check) @data('10000000111111大声道大厦大厦的撒大厦大厦大厦大声道', '@@!@!@!@!@!@!@@@@@@@@@@@@@@<dasdasd asd>') def test_step_003(self, phone): """超级管理员用户修改手机号为异常值""" self.json_data['phone'] = phone ret = self.service.change_user_info( self.json_data, output=True, expect=codes.SMS_VERIFICATION_CODE_ERROR) self.assertTrue(ret.check) @data('*****@*****.**', '*****@*****.**', '123') def test_step_004(self, email): """超级管理员用户修改邮箱-->此处测试管理员的邮箱没有进行校验""" self.json_data['email'] = email if '@' in email: ret = self.service.change_user_info(self.json_data, output=True) self.assertTrue(ret.check) else: ret = self.service.change_user_info( self.json_data, output=True, expect=codes.SERVER_INTERNAL_ERROR) self.assertTrue(ret.check) @data({'x': 1, 'y': 2}, {'中': 'dasd', '果盘': '123123'}) def test_step_005(self, **kwargs): """超级管理员用户非法参数""" for k, v in kwargs.items(): self.json_data[k] = v ret = self.service.change_user_info(self.json_data, output=True, expect=codes.SERVER_INTERNAL_ERROR) self.assertTrue(ret.check) @data({'account': 1}, {'account': 'dasd'}) def test_step_006(self, **kwargs): """超级管理员用户非法参数-->修改超级管理员用户名的时候提示系统管理员只允许修改密码,其实系统管理员可以修改很多东西的""" for k, v in kwargs.items(): self.json_data[k] = v ret = self.service.change_user_info( self.json_data, output=True, expect=codes.SYSTEM_ADMIN_ONLY_ALLOWED_UPDATE_PASSWORD) self.assertTrue(ret.check) @data({'account': 1}, {'account': 'dasd'}) def test_step_007(self, **kwargs): """超级管理员用户非法参数-->修改超级管理员用户名的时候提示系统管理员只允许修改密码,其实系统管理员可以修改很多东西的""" for k, v in kwargs.items(): self.json_data[k] = v ret = self.service.change_user_info( self.json_data, output=True, expect=codes.SYSTEM_ADMIN_ONLY_ALLOWED_UPDATE_PASSWORD) self.assertTrue(ret.check) @data({'name': 'admin'}) def test_step_008(self, **kwargs): """普通管理员不能修改名称为admin""" # 创建普通管理员账号 ret = self.user.create_common_admin() self.assertTrue(ret.check, '创建普通管理员返回状态码跟预期不符,创建失败') self.assertTrue(ret.response.id is not None, '创建普通管理员id为空,创建失败') try: # 登陆普通管理员账号获取change user info的源数据 self.assertTrue(self.user.login_common_admin().check, '登陆普通管理员账号失败') json_data = make_user_info(ret.response.id) # 修改接口名称 for k, v in kwargs.items(): json_data[k] = v new_ret = self.service.change_user_info( json_data, output=True, expect=codes.COMMON_USER_NOT_ALLOWED_TO_USR_NAME_ADMIN) self.assertTrue(new_ret.check) finally: # 登陆超级管理员账号 self.assertTrue(self.user.login_super_admin().check) # 删除普通管理员账号 self.assertTrue( self.user.delete_single_user(ret.response.id).check) @data({'name': 'admin'}) def test_step_009(self, **kwargs): """普通用户不能修改名称为admin""" ret = self.user.create_common_user() self.assertTrue(ret.check, '创建普通用户返回状态码跟预期不符,创建失败') self.assertTrue(ret.response.id is not None, '创建普通用户id为空,创建失败') try: # 登陆普通用户号获取change user info的源数据 self.assertTrue(self.user.login_common_user().check, '登陆普通用户账号失败') json_data = make_user_info(ret.response.id) # 修改接口名称 for k, v in kwargs.items(): json_data[k] = v self.assertTrue( self.service.change_user_info( json_data, output=True, expect=codes.COMMON_USER_NOT_ALLOWED_TO_USR_NAME_ADMIN). check) finally: # 登陆超级管理员账号 self.assertTrue(self.user.login_super_admin().check) # 删除普通管理员账号 self.assertTrue( self.user.delete_single_user(ret.response.id).check)
if not '-' in age: raise ValueError('Invalid format. Try again.') age = list(map(int, age.split('-'))) if age[0] > age[1]: reversed(age) if age[0] < 18: age[0] = 18 print("We won't search among kids. Let's start from 18") if age[1] > 120: age[1] = 120 print( "We don't judge you, but we can't find such old people. Let's put 120 y.o. as maximum, that will be enough for you." ) sexis = {'b': 2, 'g': 1, 'd': 0} sex = input( "Are you searching for boys / girls / doesn't matter [b/g/d]?: ") if not sex in ['b', 'g', 'd']: raise ValueError('Invalid format. Try again') context = { 'user_id': user_id, 'age': age, 'sex': sexis[sex], 'fields': 'sex, bdate, city, career, universities, schools, common_count, personal'\ 'connections, activities, interests, music, movies, tv, books, games, about, photo_max', } lonely_user = User(context['user_id'], context['fields']) db_api = DB(context['user_id']) main(lonely_user, context)
rst = make_response(fun(*args, **kwargs)) rst.headers['Access-Control-Allow-Origin'] = '*' rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE' allow_headers = "Referer,Accept,Origin,User-Agent" rst.headers['Access-Control-Allow-Headers'] = allow_headers return rst return wrapper_fun ''' # from flask import Blueprint from api.index import api from api.user import User # from api.index import api API = api() user = User() charset = "UTF-8" # # response.setCharacterEncoding(charset); app = Flask(__name__) # CORS(app, supports_credentials=True) import api.index @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,session_id') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS,HEAD') # 这里不能使用add方法,否则会出现 The 'Access-Control-Allow-Origin' header contains multiple values 的问题 response.headers['Access-Control-Allow-Origin'] = '*'
def jwt_identity(payload): return User.get_by_id(payload['identity'])
def get_current_user(): if 'user_id' not in session: return None return User.get_by_id(session['user_id'])
) urlpatterns += format_suffix_patterns(patterns( '', url(r'api/v1/$', Meta.as_view()), url(r'api/v1/version/$', Version.as_view()), url(r'^api/v1/maintenance/$', MaintenanceRecordList.as_view(), name='maintenance-record-list'), url(r'^api/v1/maintenance/(?P<record_id>\d+)/$', MaintenanceRecord.as_view(), name='maintenance-record'), url(r'^api/v1/notification/$', NotificationList.as_view()), url(r'^api/v1/user/$', atmo_valid_token_required(UserManagement.as_view())), url(r'^api/v1/user/(?P<username>.*)/$', User.as_view()), url(r'^api/v1/profile/$', Profile.as_view(), name='profile'), url(r'^api/v1/provider/(?P<provider_id>\d+)/occupancy/$', Occupancy.as_view()), url(r'^api/v1/provider/(?P<provider_id>\d+)/hypervisor/$', Hypervisor.as_view()), url(r'^api/v1/group/$', GroupList.as_view()), url(r'^api/v1/group/(?P<groupname>.*)/$', Group.as_view()), url(r'^api/v1/tag/$', TagList.as_view()), url(r'^api/v1/tag/(?P<tag_slug>.*)/$', Tag.as_view()), url(r'^api/v1/application/$', ApplicationListNoAuth.as_view(), name='application-list-no-auth'),
#from api.resources import Resource from api.task import Task from api.user import User #from api.advice import Advice import falcon def generic_error_handler(ex, req, resp, params): if isinstance(ex, falcon.HTTPNotFound): raise falcon.HTTPNotFound(description='Not Found') elif isinstance(ex, falcon.HTTPMethodNotAllowed): raise falcon.HTTPMethodNotAllowed(falcon.HTTP_405, description='Method Not Allowed') else: raise app = falcon.API( # middleware=[ # AuthMiddleware() # ] ) #app.add_route('/example', Resource()) app.add_route('/task',Task()) app.add_route('/user',User()) #app.add_route('/advice",Advice()) app.add_error_handler(Exception, generic_error_handler)
from api.user import User from pprint import pprint if __name__ == '__main__': # Enter your login and password. login = '' password = '' # You should get a token. token = '30fb3f5f75a96fbe146aa679e9f87c5763e4cdf981220488e74df174f70c75c140b5659783b587440edb2' _user = User( login, password, token, 'https://vk.com/paramime', ) print(_user.add_like_photo('saved', cnt=100)) # print(_user.add_comment('Динак идёт пить пиво', 2))
def authenticate(username, password): user = User.find_by_username(username) if user and user.password == password: return user
def identity(payload): user_id = payload['identity'] return User.find_by_id(user_id)