def auth_add(): form = AuthAddForm(request.form) if request.method == 'POST' and form.validate(): with db.auto_commit(): auth = Auth() auth.set_attr(form.data) db.session.add(auth) Oplog('添加权限:' + auth.name) flash('添加权限成功~', 'ok') return redirect(url_for('admin.auth_add')) return render_template('admin/auth_add.html', form=form)
def add(application): """Register a new application allowed to work with the API""" a = Auth.query.filter_by(application=application).first() if not a: a = Auth() a.application = application db.session.add(a) db.session.commit() print( '>>> Application {} registered. Please use the following token to connect: {}' .format(a.application, a.get_token()))
def add(): form = AuthForm() if form.validate_on_submit(): data = form.data auth = Auth.query.filter_by(name=data['name']).count() if auth == 1: flash("权限已经存在!", "err") return redirect(url_for("auth.add")) auth = Auth(data) auth.save() flash("标签添加成功!", "ok") redirect(url_for('.add')) return render_template('admin/auth/add.html', form=form)
def update_auth_list(): '''添加多个权限(到某个权限组)''' validator = AuthsValidator().validate_for_api() auth_list = [get_ep_name(id) for id in validator.auth_ids.data] group_id = validator.group_id.data for auth in auth_list: one = AuthModel.get(group_id=group_id, auth=auth) if not one: meta = find_auth_module(auth) AuthModel.create(group_id=group_id, auth=meta.auth, module=meta.module) return Success(error_code=1)
def create_group(): '''新建权限组''' validator = BaseValidator.get_json() name = validator['name'] # 权限组名 auth_ids = validator['auth_ids'] # 权限IDs auth_list = [get_ep_name(auth_id) for auth_id in auth_ids] # 权限名列表 info = validator['info'] # 权限组名描述 group = GroupModel.create(name=name, info=info) for auth in auth_list: meta = find_auth_module(auth) if meta: AuthModel.create(auth=meta.auth, module=meta.module, group_id=group.id) return Success(error_code=1)
def append_auth_list(group_id, auth_ids=[]): ''' :param group_id: 权限组id :param auth_ids: 权限id数组 :return: ''' auth_name_list = [get_ep_name(id) for id in auth_ids] with db.auto_commit(): for name in auth_name_list: one = Auth.get(group_id=group_id, name=name) if not one: meta = find_auth_module(name) Auth.create(group_id=group_id, name=meta.name, module=meta.module, commit=False)
def __init__(self): # Request self.request = request # Jsonify self.jsonify = jsonify # Authentication self.auth = Auth() # Flask Framework self.flask = Flask(__name__) # MongoDB self.mongo = Mongo(self.auth)
def is_in_auth_scope(group_id, endpoint): meta = current_app.config['EP_META'].get(endpoint) allowed = False if meta: allowed = AuthModel.get(group_id=group_id, auth=meta.auth, module=meta.module) return True if allowed else False
def create_group(name, auth_ids, info): ''' :param name: 权限组名 :param auth_ids: 权限ids :param info: 权限组名描述 :return: ''' auth_list = [get_ep_name(auth_id) for auth_id in auth_ids] # 权限名列表 with db.auto_commit(): group = Group.create(name=name, info=info, commit=False) db.session.flush() for auth in auth_list: meta = find_auth_module(auth) if meta: Auth.create(auth=meta.name, module=meta.module, group_id=group.id, commit=False)
def before_request_auth(): if Config.PRODUCTION_MODE == 'yes': if request.method != 'OPTIONS': if 'application' in request.headers and 'token' in request.headers: a = Auth.verify_token(request.headers['token']) if a is None: abort(401) if a.application.lower( ) != request.headers['application'].lower(): abort(403) else: abort(401)
def setUp(self): # self.db, application.config['DATABASE'] = tempfile.mkstemp() application.config.from_pyfile('config/test.cfg') application.config['TESTING'] = True self.client = application.test_client() self.db = db self.db.create_all() self.auth = Auth.create( email="*****@*****.**", password='******', token='SUmnfqii5wcuJz8WZrWJw66AsE9', )
def login(): # データの受け取り receive_data = request.get_json() e_mail = receive_data["e-mail"] password = receive_data["password"] next_page = receive_data["next-page"] # アドレスが登録されていないエラー if not e_mail in getAllEmailFromClient(): return jsonify({"login_error": 1}) # パスワードが誤っているエラー if not isSuccessPass(e_mail, password): return jsonify({"login_error": 2}) # ユーザー情報を取得 clientInformation = getClientByEmail(e_mail) # 管理者権限がありません if next_page in ADMINISTRATOR_AUTHORITY.split( "/") and clientInformation.admin == False: return jsonify({"login_error": 3}) # ログイン login_user(Auth()) # # ユーザー情報を成形(ほぼそのまま) clientInformationToReact = { "last-name": clientInformation.last_name, "first-name": clientInformation.first_name, "role": clientInformation.role, "belonging": clientInformation.belonging, "work-code": clientInformation.work_code, "finances": clientInformation.finance, "e-mail": clientInformation.e_mail, "reference_list": clientInformation.reference_list, "first-name-reading": clientInformation.first_name_reading, "last-name-reading": clientInformation.last_name_reading, "gender": clientInformation.gender, "nationality": clientInformation.nationality, "birthday": clientInformation.birthday, } return jsonify({ "login_error": 0, "user_information": clientInformationToReact })
def test_model_auth(self): # create a = Auth() a.application = 'test' db.session.add(a) db.session.commit() self.assertTrue(a.id > 0, 'id must be defined, but it is not.') # find a = Auth.query.filter_by(application='test').first() self.assertIsNotNone(a, 'we did not find the test application') # get token token = a.get_token() self.assertIsNot(token, '', 'token is not provided') # get another object b = Auth.query.get(a.id) self.assertIsNotNone( b, 'we did not retrieve the test application by its id') # verify objects equals self.assertEqual(str(a), str(b), 'error: a is not b') # check token of a self.assertIsNotNone(a.verify_token(token), 'invalid token provided (a)') self.assertIsNotNone(b.verify_token(token), 'invalid token provided (b)') self.assertEqual( a.verify_token(token).application, 'test', 'a check token did not send the proper application') # check bad token self.assertIsNone(a.verify_token('i am a bad token'), 'check invalid token failed') # must not find undefined application c = Auth.query.filter_by(application='totolastiko').first() self.assertIsNone( c, 'search for undefined application did not fails as expected') d = Auth.query.get(123456) self.assertIsNone( d, 'get with value 123456 retrieve something but it should not') # delete e = Auth.query.get(a.id) self.assertEqual(e.application, 'test', 'cannot retrieve application test') db.session.delete(e) db.session.commit() f = Auth.query.get(a.id) self.assertIsNone(f, 'test application was not deleted')
def post(self): args = self.reqparse.parse_args() auth = Auth.query.filter_by(email=args.get('email')).first() if auth: return 'the %s already exists' % auth.email, 404 data = self.api_gateway.post(f'/consumers', data={ 'username': args.get('email'), }) auth = Auth.create(id=data.get('id'), email=args.get('email'), password=args.get('password')) response = self.account_api.post(f'/account-service/users', data=dict(args, **{'auth_id': auth.id})) return { "id": data.get('id'), "email": args.get('email'), "token": args.get('token'), "first_name": args.get('first_name'), "last_name": args.get('last_name'), "role": args.get('role') }
def excel(): # check the method if request.method == 'POST': # standard response response = {'res_tab': '', 'res': '', 'err': '', 'jwt_token': ''} # get request data email = request.form['email'] f = request.files['sample_file'] file_name = f.filename # check email and extension file if email != '' and file_name.endswith('.xlsx'): # check the e-mail auth = Auth(email) # try create jwt if auth.createJwt(): response['jwt_token'] = str(auth.jwt_token) # get worksheet data wb = load_workbook(f) ws = wb[wb.sheetnames[0]] # first ws ws_tabs = sorted(wb.sheetnames) # tabs # get only values ws_values = [] for row in ws.iter_rows(min_row=1, max_col=3, max_row=10, values_only=True): if row[0] is not None: ws_values.append(row) # slice data keys = ws_values[:1][0] values = ws_values[1:] data = [] # get dict for item in values: data.append(dict(zip(keys, item))) response['res_tab'] = ws_tabs response['res'] = data return response else: response['err'] = 'INVALID EMAIL' return response else: response['err'] = 'INVALID INPUT DATA' return response else: response['err'] = 'INVALID METHOD' return response
def put(self, id): args = self.reqparse.parse_args() auth = Auth.get(id) if auth and (not auth.is_delete) and auth.update(**args): return 'update %s success' % auth.email, 202 return ' %s not found' % auth.email, 404
def delete(self, id): auth = Auth.get(id) if auth and (not auth.is_delete): auth.remove() return "Delete success", 204 return "Not Found", 404
def get(self, id): auth = Auth.get(id) if auth and (not auth.is_delete): return marshal(auth, auth_fields), 201 return "Not Found"
def load_user(user_id): return Auth()
class App: def __init__(self): # Request self.request = request # Jsonify self.jsonify = jsonify # Authentication self.auth = Auth() # Flask Framework self.flask = Flask(__name__) # MongoDB self.mongo = Mongo(self.auth) # Success def success(self, data): if data: if '_id' in data: data.pop('_id') return self.response({'message': 'Ok', 'result': data}, 200) else: return self.response({'message': 'Not found'}, 404) def result(self, action, base, args=False): p = self.auth.parse(request.headers.get('authorization')) if p: # User u = self.mongo.app.user(p['payload']['id']) # Check token if u and u['token'] == p['token']: # Verify token v = self.auth.verify(u['secret'], p['payload'], p['signature']) if v == True: # return self.success(self.generatetoken({'days': 6})) # return self.success(self.auth.encode('sendtics.com') +'.'+ self.auth.encode('users')) return self.success( getattr(self.mongo.api, action)( self.auth.encode(p['payload']['domain']) + '.' + self.auth.encode(base), args)) else: return self.unauthorized(v['error']) else: return self.unauthorized('Invalid Token') return self.unauthorized('Unauthorized') # Unauthorized def unauthorized(self, message): return self.response({'message': message}, 401) # Response def response(self, data, status): if data and status: data['status'] = status return make_response(jsonify(data), status)
def test_create_auth(self): self.assertEqual(Auth.query.count(), 1) self.auth = Auth.create(password='******', email='*****@*****.**') self.assertEqual(Auth.query.count(), 2)