def put(self, user_id): raw_data = request.get_json() user = User.query.options(joinedload('roles')).filter_by(id=user_id).first() if not user: return Result.error('User does not exist') user.first_name = raw_data['first_name'] user.last_name = raw_data['last_name'] user.roles = [] if raw_data['attributes']: if raw_data['attributes'] and 'access' in raw_data['attributes']: user.attributes.user_access = json.dumps(raw_data['attributes']['access']) if raw_data['attributes'] and 'preferences' in raw_data['attributes']: user.attributes.user_preferences = json.dumps(raw_data['attributes']['preferences']) if raw_data['roles']: for role in Role.query.filter(Role.id.in_( list(map( lambda r: r['id'], raw_data['roles']) ))): user.roles.append(role) db.session.commit() emit('USER_WS_CHANGED', {'data': user.id}, namespace='/' + str(user.id), broadcast=True) return Result.success()
def delete(self): role_id = request.get_json() try: Role.query.filter_by(id=role_id).delete() db.session.commit() except IntegrityError as e: return Result.error('integrity constraint', 409) return Result.success()
def get(self, user_token): jwt = UserToken.query.filter_by(token=user_token).first() time = datetime.datetime.utcnow() if jwt and jwt.expires > time: return Result.custom({'isValid': True}, 200) return Result.custom({'isValid': False}, 400)
def put(self, installation_id): c = Installation.query.filter_by(id=installation_id).first() if not c: raise HttpNotFoundException() json = get_fillable(Installation, **request.get_json()) for field, value in json.items(): setattr(c, field, value) data = request.get_json().copy() if 'panels' in data: InstallationPanelModel.query.filter_by( installation_id=installation_id).delete() for panel in data['panels']: db.session.add( InstallationPanelModel(installation_id=installation_id, model_id=panel['id'], quantity=int(panel['quantity']), serials=panel['serials'])) if 'inverters' in data: InstallationInverterModel.query.filter_by( installation_id=installation_id).delete() for inverter in data['inverters']: db.session.add( InstallationInverterModel(installation_id=installation_id, model_id=inverter['id'], quantity=int( inverter['quantity']), serials=inverter['serials'])) db.session.commit() return Result.success(code=201)
def put(self): data = request.get_json() role = Role.query.filter_by(id=data['id']).first() role.permissions = json.dumps(data['permissions']) db.session.commit() emit('ROLE_WS_CHANGED', {'data': role.name}, namespace='/' + role.name, broadcast=True) return Result.success()
def post(self): category = request.form.get('category') name = request.form.get('name') installation_id = request.form.get('installation_id') file = request.files.get('file') if category not in DOCUMENT_CATEGORIES: raise HttpException('Invalid Category') extension = max(guess_all_extensions(file.content_type), key=len) key_name = 'documents/{}/{}'.format( installation_id, hashlib.sha256( (str(datetime.utcnow().timestamp()) + name + extension + installation_id).encode('utf8')).hexdigest() + extension) s3 = Storage(configs.UPLOAD_FILE_BUCKET) inst_doc = InstallationDocument(name=name, installation_id=installation_id, category=category, object_key=key_name) s3.put_new(file.read(), key_name, file.content_type) file.close() db.session.add(inst_doc) db.session.commit() return Result.success()
def post(self): c = CustomerProject( **get_fillable(CustomerProject, **request.get_json())) db.session.add(c) db.session.commit() return Result.id(c.id)
def get(self): page = request.args.get('page', 1) total_pages = 1 q = request.args.get('query') if q: users = User.query.filter( (User.first_name.like('%' + q + '%')) | (User.last_name.like('%' + q + '%')) | (User.email.like('%' + q + '%')) ).all() else: paginator = Paginator(User.query, int(page), request.args.get('orderBy'), request.args.get('orderDir')) total_pages = paginator.total_pages users = paginator.get_result() user_list = list(map(lambda user: { 'first_name': user.first_name, 'last_name': user.last_name, 'name': user.first_name + ' ' + user.last_name, 'id': user.id, 'email': user.email, 'attributes': get_user_attr(user), 'roles': list(map(lambda r: { 'name': r.name, 'id': r.id }, user.roles)) }, users)) return Result.paginate(user_list, page, total_pages)
def post(self): auth = request.authorization if not auth or not auth.username or not auth.password: return Result.error('Could not verify') user = User.query.filter_by(email=auth.username.lower()).first() if not user: return Result.error('Could not verify') if user.password_correct(auth.password): session['logged_in'] = True session['user_email'] = user.email return user_to_dict(user) return Result.error('Could not verify')
def delete(self): if 'logged_in' in session: session.pop('logged_in') session.pop('user_email') return {} return Result.error('no session', 401)
def access_decorator(*args, **kwargs): if not request.user: return Result.error('Invalid user', 401) has_access = False for role in request.user.roles: for name, grant in role.get_permissions.items(): if name == permissions[request.endpoint]: for access in grant: if access == access_map[request.method]: has_access = True break if not has_access: return Result.error('Access denied', 403) return f(*args, **kwargs)
def decorated(*args, **kwargs): token = None if 'X-System-Token' in request.headers: token = request.headers.get('X-SYSTEM-TOKEN') if not token or token != current_app.config['SECRET_KEY']: return Result.error('Token is missing!', 401) return f(*args, **kwargs)
def get(self): ins_id = request.args.get('installation_id') if ins_id is None: raise HttpException('Missing required query string', 400) follow_ups = InstallationFollowUp.query.options( joinedload('alert_group'), joinedload('alert_group.users').load_only(User.first_name, User.last_name, User.id, User.email), lazyload('alert_group.users.roles'), lazyload('alert_group.users.attributes'), joinedload('comments'), joinedload('comments.user').load_only(User.first_name, User.last_name, User.id, User.email), lazyload('comments.user.roles'), lazyload('comments.user.attributes'), ).filter_by(installation_id=ins_id).all() result = [] for follow_up in follow_ups: result.append({ 'next_follow_up': str(follow_up.next_follow_up.isoformat()), 'alert_group': { 'name': follow_up.alert_group.name, 'users': [{ 'name': '{} {}'.format(user.first_name, user.last_name), 'email': user.email, 'id': user.id } for user in follow_up.alert_group.users] }, 'comments': [{ 'comment': comment.comment, 'date': str(comment.date.isoformat()), 'user': { 'name': '{} {}'.format(comment.user.first_name, comment.user.last_name), 'email': comment.user.email, 'id': comment.user.id } } for comment in follow_up.comments] }) return Result.custom(result)
def decorated(*args, **kwargs): token = None if 'X-Access-Token' in request.headers: token = request.headers['X-ACCESS-TOKEN'] if not token: return Result.error('Token is missing!', 401) try: data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256']) current_user = User.query.options( joinedload('roles')).filter_by(email=data['email']).first() except Exception: return Result.error('Token is invalid!', 401) request.user = current_user return f(*args, **kwargs)
def post(self): role = request.get_json() if not role: return Result.error('name is required') current = Role.query.filter_by(name=role).count() if current > 0: return Result.error('name already in used') role = Role(name=role.title()) db.session.add(role) db.session.commit() return { 'id': role.id, 'name': role.name, 'permissions': role.permissions }
def put(self, project_id): project = CustomerProject.query.filter_by(id=project_id).first() if not project: raise HttpNotFoundException() json = get_fillable(CustomerProject, **request.get_json()) for field, value in json.items(): setattr(project, field, value) db.session.commit() return Result.success(code=201)
def put(self, customer_id): c = Customer.query.filter_by(id=customer_id).first() if not c: raise HttpNotFoundException() json = get_fillable(Customer, **request.get_json()) for field, value in json.items(): setattr(c, field, value) db.session.commit() return Result.success(code=201)
def put(self): data = request.get_json() if data is None or 'email' not in data: raise HttpException('Missing email') user = User.query.filter_by(email=data['email']).first() if user is not None: send_user_token_email(user, 'Actualiza tu contraseña', 'email/change_password.html') # for security reasons, even if user does not exist, we return a success call return Result.success()
def get(self): if 'logged_in' in session: try: user = User.query.filter_by(email=session['user_email']).first() except (ProgrammingError, OperationalError): return Result.error('install', 501) if user: return user_to_dict(user) else: try: # the second param is a function that would raise exception # if table not exist we cache it to avoid multiple # executions when a user is just logged out. Cache.remember('users.count', User.query.count, 24 * 60 * 60) except (ProgrammingError, OperationalError): return Result.error('install', 501) return Result.error('no session', 403)
def post(self): data = request.get_json() group = UserGroup(name=data['name'].upper().strip()) users = User.query.filter(User.id.in_(data['ids'])).all() for user in users: group.users.append(user) db.session.commit() return Result.id(group.id)
def get(self, customer_id=None): if customer_id: customer = Customer.query.options( joinedload('customer_projects'), joinedload('customer_projects.installations'), joinedload( 'customer_projects.installations.panels.panel_model'), joinedload( 'customer_projects.installations.inverters.inverter_model' ), joinedload( 'customer_projects.installations.installation_documents'), joinedload('customer_projects.installations.status'), joinedload('customer_projects.installations.financing'), joinedload('customer_projects.installations.financing.status'), joinedload( 'customer_projects.installations.financing.financial_entity' )).filter_by(id=customer_id) return Result.model(customer.first()) page = request.args.get('page', 1) total_pages = 1 q = request.args.get('query') if q: customers = Customer.query.filter( (Customer.first_name.like('%' + q + '%')) | (Customer.last_name.like('%' + q + '%')) | (Customer.primary_email.like('%' + q + '%')) | (Customer.primary_phone.like('%' + q + '%'))( Customer.identification_number.like('%' + q + '%'))).all() else: paginator = Paginator(Customer.query, int(page), request.args.get('orderBy', 'last_name'), request.args.get('orderDir', 'desc')) total_pages = paginator.total_pages customers = paginator.get_items() return Result.paginate(customers, page, total_pages)
def post(self): data = request.get_json().copy() if 'request_date' in data: data['request_date'] = local_to_utc(data['request_date']) if 'response_date' in data: data['response_date'] = local_to_utc(data['response_date']) financing = InstallationFinancing( **get_fillable(InstallationFinancing, **data)) db.session.add(financing) db.session.commit() return Result.id(financing.id)
def get(self): total_unread = UserMessage.query.filter_by(user_id=request.user.id, read=False).count() page = request.args.get('page', 1) paginator = Paginator( UserMessage.query.filter_by(user_id=request.user.id), int(page), request.args.get('orderBy', 'date'), request.args.get('orderDir', 'desc') ) total_pages = paginator.total_pages return Result.custom( {'list': paginator.get_items(), 'page': page, 'total_pages': total_pages, 'total_unread': total_unread} )
def delete(self, installation_id): object_key = request.get_json()['object_key'] doc = InstallationDocument.query.filter_by( object_key=object_key, installation_id=installation_id).first() if not doc: raise HttpException('Invalid id') db.session.delete(doc) db.session.commit() s3 = Storage(configs.UPLOAD_FILE_BUCKET) s3.remove(object_key) return Result.success()
def put(self, installation_id): status = InstallationStatus.query.filter_by( installation_id=installation_id).first() if status is None: raise HttpNotFoundException() update = request.get_json().copy() for field, value in update.items(): if isinstance(value, str): setattr(status, field, local_to_utc(value)) elif isinstance(value, bool): setattr(status, field, value) db.session.commit() return Result.success(code=201)
def put(self, installation_id): financing = InstallationFinancing.query.filter_by( installation_id=installation_id).first() if financing is None: raise HttpNotFoundException() data = request.get_json().copy() if 'request_date' in data: data['request_date'] = local_to_utc(data['request_date']) if 'response_date' in data: data['response_date'] = local_to_utc(data['response_date']) for field, value in data.items(): setattr(financing, field, value) db.session.commit() return Result.success(code=201)
def put(self, installation_follow_up_id): data = request.get_json().copy() follow_up = InstallationFollowUp.query.filter_by( id=installation_follow_up_id).first() if follow_up is None: raise HttpNotFoundException() for key, value in data.items(): if key in InstallationFollowUp.fillable: setattr(follow_up, key, value) if 'comment' in data: follow_up.comments.append( InstallationFollowUpComment(user_id=request.user.id, comment=data['comment'])) db.session.commit() return Result.success(code=201)
def post(self): data = request.get_json() ut = UserToken.query.filter_by(token=data['token']).first() if not ut or ut.expires <= datetime.datetime.utcnow(): raise HttpException('Invalid token') if ut.target != request.base_url: raise HttpException('Invalid target') parsed = r'^(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*(),.?":{}|<>])' if len(data['pw']) < 6 or not re.match(parsed, data['pw']) or data['pw'] != data['pw2']: raise HttpException('Invalid password') user = ut.user user.password = data['pw'] user.hash_password() ut.expires = datetime.datetime.utcnow() db.session.commit() return Result.success()
def get(self, installation_id=None): page = int(request.args.get('page', 1)) if installation_id: docs = Installation.query.filter_by(id=installation_id).first() if docs: s3 = Storage(configs.UPLOAD_FILE_BUCKET) row = dict(docs) row['signed_urls'] = [] if docs: [ row['signed_urls'].append({ 'category': installation_document.category, 'name': installation_document.name, 'object': installation_document.object_key, 'url': Cache.remember( 'f_%s' % installation_document.object_key, lambda: s3.sign_url(installation_document. object_key), 14400) }) for installation_document in docs.installation_documents ] return row else: raise HttpNotFoundException() else: paginator = Paginator(InstallationDocument.query, page, request.args.get('orderBy'), request.args.get('orderDir')) total_pages = paginator.total_pages result = paginator.get_items() return Result.paginate(result, page, total_pages)
def put(self): user = request.user raw_data = request.get_json() if 'first_name' in raw_data: user.first_name = raw_data['first_name'] if 'last_name' in raw_data: user.last_name = raw_data['last_name'] access = user.attributes.access preferences = user.attributes.preferences if raw_data['attributes']: if 'access' in raw_data['attributes']: user.attributes.user_access = json.dumps({**access, **raw_data['attributes']['access']}) if 'preferences' in raw_data['attributes']: user.attributes.user_preferences = json.dumps({**preferences, **raw_data['attributes']['preferences']}) db.session.commit() emit('USER_WS_CHANGED', {'data': user.id}, namespace='/' + str(user.id), broadcast=True) return Result.success()