def get_record_detail(record_id): from api.lib.cmdb.ci import CIManager record = OperationRecord.get_by_id(record_id) or abort( 404, "Record <{0}> is not found".format(record_id)) username = UserCache.get(record.uid).nickname or UserCache.get( record.uid).username timestamp = record.created_at.strftime("%Y-%m-%d %H:%M:%S") attr_history = AttributeHistory.get_By(record_id=record_id, to_dict=False) rel_history = CIRelationHistory.get_by(record_id=record_id, to_dict=False) attr_dict, rel_dict = dict(), {"add": [], "delete": []} for attr_h in attr_history: attr_dict[AttributeCache.get(attr_h.attr_id).alias] = dict( old=attr_h.old, new=attr_h.new, operate_type=attr_h.operate_type) for rel_h in rel_history: first = CIManager.get_ci_by_id(rel_h.first_ci_id) second = CIManager.get_ci_by_id(rel_h.second_ci_id) rel_dict[rel_h.operate_type].append( (first, RelationTypeCache.get(rel_h.relation_type_id).name, second)) return username, timestamp, attr_dict, rel_dict
def get_records(start, end, username, page, page_size): records = db.session.query(OperationRecord).filter( OperationRecord.deleted.is_(False)) numfound = db.session.query(db.func.count(OperationRecord.id)).filter( OperationRecord.deleted.is_(False)) if start: records = records.filter(OperationRecord.created_at >= start) numfound = numfound.filter(OperationRecord.created_at >= start) if end: records = records.filter(OperationRecord.created_at <= end) numfound = records.filter(OperationRecord.created_at <= end) if username: user = UserCache.get(username) if user: records = records.filter(OperationRecord.uid == user.uid) else: return abort(404, "User <{0}> is not found".format(username)) records = records.order_by(-OperationRecord.id).offset( page_size * (page - 1)).limit(page_size).all() total = len(records) numfound = numfound.first()[0] res = [] for record in records: _res = record.to_dict() _res["user"] = UserCache.get( _res.get("uid")).nickname or UserCache.get( _res.get("uid")).username attr_history = AttributeHistory.get_by(record_id=_res.get("id"), to_dict=False) _res["attr_history"] = [ AttributeCache.get(h.attr_id).attr_alias for h in attr_history ] rel_history = CIRelationHistory.get_by(record_id=_res.get("id"), to_dict=False) rel_statis = {} for rel in rel_history: if rel.operate_type not in rel_statis: rel_statis[rel.operate_type] = 1 else: rel_statis[rel.operate_type] += 1 _res["rel_history"] = rel_statis res.append(_res) return numfound, total, res
def _auth_with_session(): if isinstance(getattr(g, 'user', None), User): login_user(g.user) return True if "acl" in session and "userName" in (session["acl"] or {}): login_user(UserCache.get(session["acl"]["userName"])) return True return False
def validate(ticket): """ Will attempt to validate the ticket. If validation fails, then False is returned. If validation is successful, then True is returned and the validated username is saved in the session under the key `CAS_USERNAME_SESSION_KEY`. """ cas_username_session_key = current_app.config['CAS_USERNAME_SESSION_KEY'] current_app.logger.debug("validating token {0}".format(ticket)) cas_validate_url = create_cas_validate_url( current_app.config['CAS_VALIDATE_SERVER'], current_app.config['CAS_VALIDATE_ROUTE'], url_for('cas.login', _external=True), ticket) current_app.logger.debug( "Making GET request to {0}".format(cas_validate_url)) try: response = urlopen(cas_validate_url).read() ticketid = _parse_tag(response, "cas:user") strs = [s.strip() for s in ticketid.split('|') if s.strip()] username, is_valid = None, False if len(strs) == 1: username = strs[0] is_valid = True user_info = json.loads(_parse_tag(response, "cas:other")) current_app.logger.info(user_info) except ValueError: current_app.logger.error("CAS returned unexpected result") is_valid = False return is_valid if is_valid: current_app.logger.debug("valid") session[cas_username_session_key] = username user = UserCache.get(username) session["acl"] = dict( uid=user_info.get("uuid"), avatar=user.avatar if user else user_info.get("avatar"), userId=user_info.get("id"), userName=user_info.get("name"), nickName=user_info.get("nickname"), parentRoles=user_info.get("parents"), childRoles=user_info.get("children"), roleName=user_info.get("role")) session["uid"] = user_info.get("uuid") current_app.logger.debug(session) current_app.logger.debug(request.url) else: current_app.logger.debug("invalid") return is_valid
def _auth_with_ip_white_list(): ip = request.remote_addr key = request.values.get('_key') secret = request.values.get('_secret') if not key and not secret and ip.strip() in current_app.config.get( "WHITE_LIST", []): # TODO user = UserCache.get("worker") login_user(user) return True return False
def login(): """ This route has two purposes. First, it is used by the user to login. Second, it is used by the CAS to respond with the `ticket` after the user logs in successfully. When the user accesses this url, they are redirected to the CAS to login. If the login was successful, the CAS will respond to this route with the ticket in the url. The ticket is then validated. If validation was successful the logged in username is saved in the user's session under the key `CAS_USERNAME_SESSION_KEY`. """ cas_token_session_key = current_app.config['CAS_TOKEN_SESSION_KEY'] if request.values.get("next"): session["next"] = request.values.get("next") _service = url_for('cas.login', _external=True, next=session["next"]) \ if session.get("next") else url_for('cas.login', _external=True) redirect_url = create_cas_login_url(current_app.config['CAS_SERVER'], current_app.config['CAS_LOGIN_ROUTE'], _service) if 'ticket' in request.args: session[cas_token_session_key] = request.args.get('ticket') if request.args.get('ticket'): if validate(request.args['ticket']): redirect_url = session.get("next") or \ current_app.config.get("CAS_AFTER_LOGIN") username = session.get("CAS_USERNAME") user = UserCache.get(username) login_user(user) session.permanent = True else: del session[cas_token_session_key] redirect_url = create_cas_login_url( current_app.config['CAS_SERVER'], current_app.config['CAS_LOGIN_ROUTE'], url_for('cas.login', _external=True), renew=True) current_app.logger.info("redirect to: {0}".format(redirect_url)) return redirect(redirect_url)
def get_by_ci_id(ci_id): res = db.session.query( AttributeHistory, Attribute, OperationRecord).join( Attribute, Attribute.id == AttributeHistory.attr_id).join( OperationRecord, OperationRecord.id == AttributeHistory.record_id).filter( AttributeHistory.ci_id == ci_id).order_by( OperationRecord.id.desc()) return [ dict(attr_name=i.Attribute.name, attr_alias=i.Attribute.alias, operate_type=i.AttributeHistory.operate_type, username=UserCache.get(i.OperationRecord.uid).nickname, old=i.AttributeHistory.old, new=i.AttributeHistory.new, created_at=i.OperationRecord.created_at.strftime( '%Y-%m-%d %H:%M:%S'), record_id=i.OperationRecord.id, hid=i.AttributeHistory.id) for i in res ]