def login(): if request.method == 'POST': data = request.json # data = request.Form username = data.get('username', None) print(username) password = data.get('password', None) org = data.get('organization', None) # first verify user in database if username in {u.name: u for u in UserBusiness.find_all_users()}: # then verify the user password if UserBusiness.verify_password(org, username, password): # user = UserBusiness.find_user_by_name(username) ret = {'access_token': create_access_token(identity=username), 'refresh_token': create_refresh_token(identity=username) } # Return the double submit values in the resulting JSON # instead of in additional cookies # resp = jsonify({ # 'access_csrf' : get_csrf_token(ret['access_token']), # 'refresh_csrf': get_csrf_token(ret['refresh_token']) # }) # Set the JWT cookies in the response resp = jsonify({'login': True}) print(ret['access_token']) set_access_cookies(resp, ret['access_token']) set_refresh_cookies(resp, ret['refresh_token']) print("done") return resp, 200 return jsonify({"msg": "Bad password"}), 403 return jsonify({"msg": "Username is not exists!"}), 404
def login(): username = request.json.get('username', None) print(username) password = request.json.get('password', None) org = request.json.get('organization', None) # first verify user in database if username not in {u.name: u for u in UserBusiness.find_all_users()}: return jsonify({"msg": "Username is not exists!"}), 401 # then verify the user password if UserBusiness.verify_password(org, username, password) is False: return jsonify({"msg": "Bad password"}), 401 # user = UserBusiness.find_user_by_name(username) if username != 'mysql' or password != '123456': return jsonify({'login': False}), 401 ret = { 'access_token': create_access_token(identity=username), 'refresh_token': create_refresh_token(identity=username) } # Create the tokens we will be sending back to the user access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) # Set the JWT cookies in the response resp = jsonify({'login': True}) print(ret['access_token']) set_access_cookies(resp, access_token, 123456789) set_refresh_cookies(resp, refresh_token) print("done") return jsonify(ret), 200
def login(): username = request.json.get('username', None) print(username) password = request.json.get('password', None) org = request.json.get('organization', None) # first verify user in database if username in {u.name: u for u in UserBusiness.find_all_users()}: return jsonify({"msg": "Username is not exists!"}), 401 # then verify the user password if UserBusiness.verify_password(org, username, password): # user = UserBusiness.find_user_by_name(username) ret = { 'access_token': create_access_token(identity=username), 'refresh_token': create_refresh_token(identity=username) } # Set the JWT cookies in the response resp = jsonify({'login': True}) print(ret['access_token']) set_access_cookies(resp, ret['access_token']) set_refresh_cookies(resp, ret['refresh_token']) print("done") return jsonify(ret), 200 return jsonify({"msg": "Bad password"}), 401
def manage(cls, user, user_group, role): # 数据库添加用户 UserBusiness.add_user(user) # 用户添加组 if user_group is not None: user.group.append(user_group) # 用户添加角色 # roles = find_all_roles() user.roles.append(role) pass
def logout(self): try: token = {'code': request.json.get('token')} userSrv = UserBusiness() userSrv.logout(token) return self.return_success('Logout realizado com sucesso.', None) except Exception as ex: return self.return_exception(ex)
def get_logged_user(self): # get user by token token = {'code': request.headers.get('token')} if token['code'] is None: return None userSrv = UserBusiness() returnedUser = userSrv.get_by_valid_token(token) return returnedUser
def list(self): try: # get logged user loggedUser = self.get_logged_user() # get and return users userSrv = UserBusiness() users = userSrv.list(loggedUser) return self.return_success('Usuários listados com sucesso.', users) except Exception as ex: return self.return_exception(ex)
def validate_token(self, email, code): try: token = {'code': code, 'user': {'email': email}} userSrv = UserBusiness() token_validation = userSrv.validate_token(token) validation_return = {'is_valid': token_validation} return self.return_success( 'Validação de token realizada com sucesso.', validation_return) except Exception as ex: return self.return_exception(ex)
def request_reset_password(self): try: credentials = {'email': request.json.get('email')} userSrv = UserBusiness() request_reset = userSrv.request_reset_password(credentials) return self.return_success( 'Um e-mail foi enviado para ' + str(credentials['email']) + ' com mais instruções.', None) except Exception as ex: return self.return_exception(ex)
def cancel_invite(self, invitation_id): try: # get logged user loggedUser = self.get_logged_user() # prepare invite to be canceled invite = {'id': invitation_id} userSrv = UserBusiness() userSrv.cancel_invite(invite, loggedUser) return self.return_success('Convite cancelado com sucesso.', None) except Exception as ex: return self.return_exception(ex)
def login(self): try: credentials = { 'email': request.json.get('email'), 'password': request.json.get('password') } userSrv = UserBusiness() login_stuff = userSrv.login(credentials) return self.return_success('Login realizado com sucesso.', login_stuff) except Exception as ex: return self.return_exception(ex)
def user_add(cls, data): user = UserBusiness.create_user(data) if type(user) == str: return user name = user.name oa = str(user.organization) # 同一个应用下,用户名唯一,也即name+org 唯一 if UserBusiness.find_user_by_org_name(oa, name): # if UserBusiness.find_user_by_name(username): return "用户已存在,请重新输入!" else: UserBusiness.add_user(user) return user
def get(self, user_id): try: # get logged user loggedUser = self.get_logged_user() # prepare user to be retrieved user = {'id': user_id} # get and return users userSrv = UserBusiness() user = userSrv.get(user, loggedUser) return self.return_success('Usuário retornado com sucesso.', user) except Exception as ex: return self.return_exception(ex)
def refresh_invite(self, user_id): try: # get logged user loggedUser = self.get_logged_user() # prepare parameters user = {'id': user_id} # refresh user invite userBus = UserBusiness() invited_user = userBus.refresh_invite(user, loggedUser) return self.return_success('Convite enviado com sucesso.', None) except Exception as ex: return self.return_exception(ex)
def update(self, user_id): try: statusId = None if request.json.get('status'): statusId = request.json.get('status')['id'] profileId = None if request.json.get('profile'): profileId = request.json.get('profile')['id'] supervisor_id = None if request.json.get('supervisor'): supervisor_id = request.json.get('supervisor')['id'] user = { 'id': user_id, 'status': { 'id': statusId }, 'profile': { 'id': profileId }, 'full_name': request.json.get('full_name'), 'email': request.json.get('email'), 'new_password': request.json.get('new_password'), 'new_password_confirmation': request.json.get('new_password_confirmation'), 'current_password': request.json.get('current_password'), 'supervisor': { 'id': supervisor_id } } # get logged user loggedUser = self.get_logged_user() userSrv = UserBusiness() userSrv.update(user, loggedUser) return self.return_success('Alterações realizadas com sucesso.', None) except Exception as ex: return self.return_exception(ex)
def remove_user_from_group(cls, user_name, group_name): user = UserBusiness.find_user_by_name(user_name) user_group = UsergroupBusiness.find_group_by_name(group_name) user.group.remove(user_group) user.modified_date = date_time print(user.name + "-从用户组-" + user_group.name + '-移除成功!') db.session.commit()
def add_user_into_group(cls, user_name, group_name): user = UserBusiness.find_user_by_name(user_name) user_group = UsergroupBusiness.find_group_by_name(group_name) user.group.append(user_group) user.modified_date = date_time print (user.name + "--添加到用户组--" + user_group.name + '--成功!') db.session.commit()
def signup(self): try: user = { 'email': request.json.get('email'), 'access_code': request.json.get('access_code'), 'password': request.json.get('password'), 'password_confirmation': request.json.get('password_confirmation') } userSrv = UserBusiness() logged_user = userSrv.signup(user) return self.return_success('Cadastro realizado com sucesso.', logged_user) except Exception as ex: return self.return_exception(ex)
def verify_auth_token(token): s = Serializer(app.config['SECRET_KEY']) try: data = s.loads(token) except SignatureExpired: return None # valid token, but expired except BadSignature: return None # invalid token user = UserBusiness.find_user_by_id(data['id']) return user
class AuthUserApi(Resource): """Classe das operação Restful POST com a busca de um usuário previamente cadastrado, para que possa ter email e senha validados para a garantia do token de autenticação""" business = UserBusiness() def post(self): user_json = request.get_json() resp = self.business.sign_in(user_json) return Response(resp, mimetype='application/json', status=200)
class UserApi(Resource): """Classe das operação Restful POST sem parâmetro da API de Usuário, que cadastra um usuário para sua posterior autenticação. Cada usuário deverá ter uma chave ID única, além de um email também único no sistema""" business = UserBusiness() def post(self): user_json = request.get_json() return Response(self.business.create_user(user_json), mimetype='application/json', status=200)
def self_update(self): try: user = { 'full_name': request.json.get('full_name'), 'email': request.json.get('email'), 'new_password': request.json.get('new_password'), 'new_password_confirmation': request.json.get('new_password_confirmation') } # get logged user loggedUser = self.get_logged_user() userSrv = UserBusiness() updated_user = userSrv.self_update(user, loggedUser) return self.return_success('Alterações realizadas com sucesso.', updated_user) except Exception as ex: return self.return_exception(ex)
def invite(self): try: # get logged user loggedUser = self.get_logged_user() # prepare user to be invited profileId = None if request.json.get( 'profile' ): #error: AttributeError: 'NoneType' object has no attribute 'get' profileId = request.json.get('profile')['id'] supervisor_id = None if request.json.get('supervisor'): supervisor_id = request.json.get('supervisor')['id'] user = { 'profile': { 'id': profileId }, 'full_name': request.json.get('full_name'), 'email': request.json.get('email'), 'company': loggedUser['company'] if loggedUser else None, 'answers': request.json.get('answers'), 'supervisor': { 'id': supervisor_id } } userSrv = UserBusiness() invited_user = userSrv.invite(user, loggedUser) return self.return_success('Convite enviado com sucesso.', invited_user) except Exception as ex: return self.return_exception(ex)
def reset_password(self, user_id=None): try: # prepare parameter according to the type of request parameters = None if not user_id: # user will reset its own passowrd reset_request = { 'token': request.json.get('token'), 'email': request.json.get('email'), 'new_password': request.json.get('new_password'), 'new_password_confirmation': request.json.get('new_password_confirmation') } userSrv = UserBusiness() userSrv.reset_own_password(reset_request) else: # get logged user logged_user = self.get_logged_user() # user will reset other user's password reset_request = { 'user': { 'id': user_id }, 'new_password': request.json.get('new_password'), 'new_password_confirmation': request.json.get('new_password_confirmation') } userSrv = UserBusiness() userSrv.reset_password(reset_request, logged_user) return self.return_success('Senha reinicializada com sucesso.', None) except Exception as ex: return self.return_exception(ex)
def find_role_by_user_name(cls, user_name): user = UserBusiness.find_user_by_name(user_name) if user is not None: for role in user.roles: yield role pass
def find_group_by_user_name(cls, username): user = UserBusiness.find_user_by_name(username) for group in user.group: if group is not None: yield group
def remove_user_by_role_name(cls, user_name, role_name): user = UserBusiness.find_user_by_name(user_name) RoleBusiness.add_user_by_role_name(user, role_name)
# blacklist.add(jti) resp = jsonify({'logout': True}) unset_jwt_cookies(resp) return resp, 200 @app.route('/api/user/<int:id>') @jwt_required def get_user(id): """ :获取用户信息 :param id: 用户id :return: json """ user = UserBusiness.find_user_by_id(id) roles = [] for i in user.roles: print(str(i)) # roles += str(i) roles.append(i.name) group = [] for j in user.group: group.append(j.name) if not user: abort(404) # return '<h1> Hello,%s </h1><h1>Role: Group</h1>' % user.name + roles return jsonify( {'username': user.name, 'phone': user.phone, 'email': user.email,
# -*- coding: UTF-8 -*- from business.user_business import UserBusiness from database.config_setting import app, date_time from services.permission_service import PermissionService from services.role_service import RoleService from services.user_group_service import UserGroupService if __name__ == '__main__': users = UserBusiness.find_all_users() for i in users: print(i) # UserBusiness.reset_password(i.name) print(date_time.strftime('%Y-%m-%d %H:%M:%S')) # PermissionService.add_permission_by_name('baidu') # PermissionService.delete_permission_by_name('除去用户') roles = PermissionService.find_roles_by_perm('添加用户') for i in roles: print(i) perms = PermissionService.find_perm_by_role('管理员Admin') for j in perms: print(j) PermissionService.add_permission_by_role_name('添加坐标', '管理员Admin') PermissionService.remove_permission_by_name('添加坐标', '管理员Admin') perms = PermissionService.find_perm_by_resource('新风设备1') for i in perms:
def users_manage(): users = UserBusiness.find_all_users()