def generate_actions(users, count): actions = list() user_count = users.__len__() - 1 for i in range(0, count): actions.append(Action(datetime.now(), users[random.randint(0, user_count)])) return actions
def crontab(request): while True: current_time = time.time() print "pulling..." rjson = data.getdata('sound,temperature', current_time, DEAMON_TIME_INTERVAL, 10) averageSound = calcAver(rjson['data']['datastreams'][0]['datapoints']) averageTem = calcAver(rjson['data']['datastreams'][1]['datapoints']) if averageSound < CRY_SOUND_THRESHOD and averageTem > INBED_TEMPERATURE_THRESHOD: action = Action(action_type='sleep') elif averageSound > CRY_SOUND_THRESHOD and averageTem > INBED_TEMPERATURE_THRESHOD: action = Action(action_type='cry') else: action = Action(action_type='missing') action.save() time.sleep(10)
def add_actions(self, actions): from time import gmtime, strftime from models import Action import json for action in actions: timestamp = strftime("%Y-%m-%d %H:%M:%S", gmtime()) new_action = Action(action=json.dumps(action), timestamp=timestamp) self.session.add(new_action) self.session.commit()
def perform_action(actions, mention): if mention.message != '': primary_action = mention.message.split(' ')[0] if primary_action in actions: if len(mention.message.split(' ')) > 1: secondary_action = mention.message.split(' ')[1] if secondary_action in actions[primary_action]: #perform both actions action_data = "TEST DOUBLE ACTION" action = Action(mention.message, action_data, mention) return action #no secondary action specified return possible options usage = "usage: " + primary_action + " " + str( actions.get(primary_action)) action = Action(mention.message, usage, mention) return action else: action = Action(mention.message, None, mention) return action
def api_close_vote(): t_settings = TimeSettings.query.first() t_settings.status = 'closed' db.session.add(t_settings) current_user = Admin.query.filter_by(email=session['user']).first() action = Action(owner=current_user.id, type='closeelection', target_type='settings', text='Closed election', target_id=1) db.session.add(action) db.session.commit() return jsonify(status="OK")
def delete(self): if (g.user.syncMaster == 0): return make_response(jsonify({'error': 'Not authorized'}), 403) print 'action-log deletetion requested' Action.query.delete() logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, '', 'Removed all actions after syncing', 'Remove actions after sync', 'L1', 0, 'Web based') db.session.add(logentry) db.session.commit() return '', 201
def post(self): print 'Opening request received' checkAccessResult = security.checkUserAccessPrivleges(datetime.datetime.now(),g.user) print "Check user privileges for opening request: " + checkAccessResult if (checkAccessResult == "Access granted."): if datetime.datetime.now() > g.user.lastAccessDateTime + datetime.timedelta(minutes=config.NODE_LOG_MERGE): g.user.lastAccessDateTime = datetime.datetime.now() logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'Opening request ( ' + str(1) + ' attempts)', 'Opening request', 'L2', 0, 'Web based', Action.ACTION_OPENING_REQUEST, 1) print "Log-entry created" try: db.session.add(logentry) db.session.commit() except: db.session.rollback() return '', 401 else: lastlogEntry = Action.query.filter_by(logType='Opening request', userMail=g.user.email).order_by(Action.date.desc()).first() if lastlogEntry is not None: print str(lastlogEntry.synced) if lastlogEntry.synced is 0: print "is not None / False" lastlogEntry.date = datetime.datetime.utcnow() lastlogEntry.actionParameter += 1 lastlogEntry.logText = 'Opening request ( ' + str(lastlogEntry.actionParameter) + ' attempts)'; else: print "is not None / True" lastlogEntry.synced = 0 lastlogEntry.date = datetime.datetime.utcnow() lastlogEntry.actionParameter = 1 lastlogEntry.logText = 'Opening request ( ' + str(lastlogEntry.actionParameter) + ' attempts)'; print str(lastlogEntry.synced) else: print "is None" print "Log-entry is in merge-range ts = " + str(datetime.datetime.now()) + " last = " + str(g.user.lastAccessDateTime) + " merge = " + str(config.NODE_LOG_MERGE) + " minutes" try: db.session.commit() except: db.session.rollback() return '', 401 backgroundWorker.requestOpening = True return 'Access granted', 201 else: print "Check user privileges for opening request: " + checkAccessResult return checkAccessResult, 201 return '', 201
def api_update_note(): strings = Strings.query.first() text = request.args.get('text') strings.note = text app.config['NOTE'] = text db.session.commit() current_user = Admin.query.filter_by(email=session['user']).first() action = Action(owner=current_user.id, type='updatenote', target_type='settings', text='Updated admin note', target_id=1) # the settings objects only have 1 id - 1 db.session.add(action) db.session.commit() return jsonify(status="OK")
def post(self): print 'RFID assign request received' # check request paremeters (form) form = RFIDTagAssignForm() if not form.validate_on_submit(): return form.errors, 422 # check admin rights if g.user.role != 1: return make_response(jsonify({'error': 'Not authorized'}), 403) user = User.query.filter_by(email=form.email.data).first() if (user == None): return make_response(jsonify({'error': 'user not found'}), 400) if form.rfidTagId.data != None and form.rfidTagId.data != '': secretString = '' for i in range(0, 16): if i != 0: secretString = secretString + '-' num = random.randrange(0, 256) secretString = secretString + format(num, '02X') user.cardID = form.rfidTagId.data user.cardSecret = secretString user.cardAuthBlock = 1 user.cardAuthSector = 4 user.cardAuthKeyA = config.RFID_GLOBAL_PASSWORD user.cardAuthKeyB = "FF-FF-FF-FF-FF-FF" print "User-secret: >" + str(user.cardSecret) + "<" print "User-keyA: >" + str(user.cardAuthKeyA) + "<" print "User-keyB: >" + str(user.cardAuthKeyB) + "<" if (backgroundWorker.assignRFIDTag(user) == False): print 'Error while assigning cardID ' + form.rfidTagId.data + ' to ' + user.firstName + ' ' + user.lastName db.session.rollback() return make_response(jsonify({'error': 'user not found'}), 400) else: logentry = Action( datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'Assign RFID-tag ' + form.rfidTagId.data + ' to ' + user.firstName + ' ' + user.lastName, 'Card administration', 'L2', 0, 'Card based') db.session.add(logentry) db.session.commit() print 'Assigned cardID ' + form.rfidTagId.data + ' to ' + user.firstName + ' ' + user.lastName return '', 201
def delete(self, id): user = User.query.filter_by(id=id).first() if user != None: print 'delete user ' + user.firstName + ' ' + user.lastName + ' (' + user.email + ') from database' logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'User ' + user.firstName + ' on ' + user.lastName + ' removed', 'User removed', 'L2', 1, 'Web based') db.session.add(logentry) db.session.commit() User.query.filter(User.id == id).delete() db.session.commit() return '', 201
def post(self): form = DoorRegistrationForm() print 'Door registration request received' if not form.validate_on_submit(): return form.errors, 422 if g.user.role != 1: return make_response(jsonify({'error': 'Not authorized'}), 403) print 'Request door info from ' + 'http://' + form.address.data + ':5000' + '/request/doorinfo' pwd = base64.b64decode(form.password.data) auth_token = 'Basic ' + base64.b64encode( "[email protected]:" + pwd) headers = {'Authorization': auth_token} try: response = requests.get('http://' + form.address.data + ':5000' + '/request/doorinfo', timeout=6, headers=headers) except: print "requested door unreachable" return 'requested door unreachable', 400 response_data = json.loads(response.content) newDoor = Door(name=response_data["name"], displayName=form.name.data, keyMask=response_data["keyMask"], address='http://' + form.address.data, local=0, password=pwd) logentry = Action( datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'Door ' + newDoor.name + ' on ' + newDoor.address + ' checked and registered', 'Door registered', 'L2', 1, 'Web based') try: db.session.add(logentry) db.session.commit() db.session.add(newDoor) db.session.commit() print "Added door to database" except IntegrityError: print "Problems to add door to database" return make_response( jsonify({'error': 'eMail already registered'}), 400) print "return new door data for request" return DoorSerializer().dump(newDoor).data
def timer_cycle(self): self.requestTimer += 1 if self.requestTimer >= 4: self.requestTimer = 0 try: self.checkRFIDTag() except Exception, e: import traceback print traceback.format_exc() logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, 'Background Worker', '*****@*****.**', 'Error: ' + str(traceback.format_exc()), 'Error occured', 'L1', 0, 'Internal') db.session.add(logentry) db.session.commit()
def api_unlock_user(): id = request.args.get('id') user = User.query.filter_by(id=id).first() user.in_timeout = False current_user = Admin.query.filter_by(email=session['user']).first() action = Action( owner=current_user.id, type='lockuser', target_type='user', text='Unlocked user ({0})'.format( user.email), target_id=user.id) db.session.add(action) db.session.commit() return jsonify(status="OK")
def api_unlock_option(): id = request.args.get('id') option = Option.query.filter_by(id=id).first() option.live = True current_user = Admin.query.filter_by(email=session['user']).first() action = Action( owner=current_user.id, type='unlockoption', target_type='option', text='unlocked option ({0})'.format( option.name), target_id=option.id) db.session.add(action) db.session.commit() return jsonify(status="OK")
def load_actions(): """Records of actions been applied to place results by users""" action_code_list = ['sav','hbh'] for i in range(250): #generating an arbitrary number of actions (250 at most) user_id = randint(1, 1000) #load_users() will generate 1000 registered users place_id = randint(1, 3030) #load_places() will generate 3030 searchable places action_code = choice(action_code_list) #checking if action has already been added to actions table action_in_db = db.session.query(Action).filter(Action.user_id==user_id, Action.place_id==place_id, Action.action_code==action_code).first() if not action_in_db: action = Action(user_id=user_id, place_id=place_id, action_code=action_code) db.session.add(action) db.session.commit()
def admin_otp(): admin = Admin.query.filter_by(email=session['user']).first() if not admin: return render_template("error.html", error="You are not logged in") method = request.method if admin.otp_enabled: if method == 'GET': return render_template("otp.html", registration=False) elif method == 'POST': token = request.form['token'] result = admin.verify_otp(token) if result: session['admin'] = True return redirect('/admin/dashboard') else: return render_template("otp.html", error=True) else: if method == 'GET': secret = admin.set_otp() db.session.commit() url = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}".format( quote(app.config['SITE_NAME']), admin.email, secret) encoded = quote_plus(url) return render_template("otp.html", registration=True, url=encoded) elif method == 'POST': token_to_check = request.form['token'] password = request.form['password'] token_verified = admin.verify_otp(token_to_check) password_verified = admin.verify_pw(password) if token_verified and password_verified: admin.otp_enabled = True action = Action( owner=admin.id, type='enable2fa', target_type='admin', text='Self-enabled 2FA', target_id=admin.id) db.session.add(action) db.session.commit() session['admin'] = True return redirect('/admin/dashboard') else: secret = admin.otp_secret url = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}".format( quote(app.config['SITE_NAME']), admin.email, secret) encoded = quote_plus(url) return render_template( "otp.html", error=True, registration=True, url=encoded)
def delete(self, id): print "requested door remove " + str(id) door = Door.query.filter_by(id=id).first() if door != None: print 'delete door ' + door.name + ' ' + door.address + ' (id=' + str(door.id) + ') from database' logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'Door (' + door.name + ' on ' + door.address + ') removed', 'Door removed', 'L2', 1, 'Web based') try: db.session.add(logentry) db.session.commit() Door.query.filter(Door.id == id).delete() db.session.commit() except: return '', 401 return '', 201
def api_enable_vote(): id = request.args.get('id') vote = Vote.query.filter_by(id=id).first() vote.counting = True db.session.commit() current_user = Admin.query.filter_by(email=session['user']).first() action = Action( owner=current_user.id, type='enablevote', target_type='vote', text='Approved vote by {0}'.format( vote.user.email), target_id=vote.id) db.session.add(action) db.session.commit() return jsonify(status="OK")
def api_disable_2fa(): current_admin = Admin.query.filter_by(email=session['user']).first() if current_admin.role != 'full': return abort(403) id = request.args.get('id') admin = Admin.query.filter_by(id=id).first() admin.otp_enabled = False admin.otp_secret = None action = Action(owner=current_admin.id, type='disable2fa', target_type='admin', text="Disabled 2FA on {0}".format(admin.name), target_id=admin.id) db.session.add(action) db.session.commit() return jsonify(status="OK")
def make_user(self, data): date = datetime.datetime.strptime(data['date'][:19], '%Y-%m-%dT%H:%M:%S') nodeName = data['nodeName'] userName = data['userName'] userMail = data['userMail'] authType = data['authType'] authInfo = data['authInfo'] logText = data['logText'] logType = data['logType'] logLevel = data['logLevel'] rollbackPoint = data['rollbackPoint'] action = data['action'] actionParameter = data['actionParameter'] action = Action(date,nodeName,userName,userMail,logText,logType,logLevel,authType,authInfo,action,actionParameter,rollbackPoint) return action
def api_create_option(): name = request.args.get('name') description = request.args.get('description') option = Option(name=name) option.update_description(description) db.session.add(option) db.session.commit() current_user = Admin.query.filter_by(email=session['user']).first() action = Action( owner=current_user.id, type='createoption', target_type='option', text='created option ({0})'.format(name), target_id=option.id) db.session.add(action) db.session.commit() return jsonify(status="OK")
def api_enable_admin(): current_admin = Admin.query.filter_by(email=session['user']).first() # only full permission can change roles if current_admin.role != 'full': return abort(403) id = request.args.get('id') admin = Admin.query.filter_by(id=id).first() admin.enabled = True action = Action( owner=current_admin.id, type='approveadmin', target_type='admin', text='Enabled admin ({0})'.format( admin.name), target_id=admin.id) db.session.add(action) db.session.commit() return jsonify(status="OK")
def actionsTable(monster, session): x = session.query(Enemy).filter_by(name=monster['name']).first() for i in monster['actions']: if 'damage_dice' in i: xtype = i['desc'].split(':')[0] if 'damage_bonus' in i: damage = f"{i['damage_dice']}+{i['damage_bonus']}" else: damage = f"{i['damage_dice']}" action = Action( enemyid=x.id, name=i['name'], attackBonus=f"+{i['attack_bonus']}", damage=damage, targetMax="one target", #no target numbers for now damageType="Bludgeoning") #no damage type for now session.add(action)
def backup_cycle(self): lasttime = self.lastBackupTime now = datetime.datetime.now() compare_time = lasttime.replace(hour=4, minute=35, second=0, microsecond=0) if compare_time > lasttime: next_time = compare_time else: next_time = compare_time + datetime.timedelta(days=1) if now > next_time or self.forceBackup == True: self.forceBackup = False print 'Doing a backup (' + str(datetime.datetime.now()) + ')' with app.app_context(): flask_alchemydumps.autoclean(True) flask_alchemydumps.create() if ConfigManager.BACKUP_ENABLE_FTP == True: print 'Doing a additional FTP backup' app.config['ALCHEMYDUMPS_FTP_SERVER'] = '' app.config['ALCHEMYDUMPS_FTP_USER'] = '' app.config['ALCHEMYDUMPS_FTP_PASSWORD'] = '' app.config['ALCHEMYDUMPS_FTP_PATH'] = '' flask_alchemydumps.create() app.config[ 'ALCHEMYDUMPS_FTP_SERVER'] = ConfigManager.ALCHEMYDUMPS_FTP_SERVER app.config[ 'ALCHEMYDUMPS_FTP_USER'] = ConfigManager.ALCHEMYDUMPS_FTP_USER app.config[ 'ALCHEMYDUMPS_FTP_PASSWORD'] = ConfigManager.ALCHEMYDUMPS_FTP_PASSWORD app.config[ 'ALCHEMYDUMPS_FTP_PATH'] = ConfigManager.ALCHEMYDUMPS_FTP_PATH print 'Next backup @' + str(next_time) + ' (' + str( datetime.datetime.now()) + ')' logentry = Action(datetime.datetime.utcnow(), ConfigManager.NODE_NAME, 'Sync Master', '*****@*****.**', 'Backup database', 'Backup', 'L1', 0, 'Internal') db.session.add(logentry) db.session.commit() self.lastBackupTime = now
def post(self): form = RegisterUserForm() print 'enter registerview' if not form.validate_on_submit(): return form.errors, 422 pwd = base64.decodestring(form.password.data) user = User(email=form.email.data, password=pwd, firstName=form.firstName.data, lastName=form.lastName.data, phone=form.phone.data, association=form.association.data) logentry = Action( datetime.datetime.utcnow(), config.NODE_NAME, user.firstName + ' ' + user.lastName, user.email, 'User registered ' + user.firstName + ' ' + user.lastName + ' ' + user.email, 'User registered', 'L2', 1, 'Web based') try: db.session.add(logentry) db.session.commit() db.session.add(user) db.session.commit() except IntegrityError: return make_response( jsonify({'error': 'eMail already registered'}), 400) # if activted send email if form.sendWelcomeMail.data != None: print 'sendWelcomeMail is ' + str(form.sendWelcomeMail.data) if form.sendWelcomeMail.data == 1: print 'try to send welcome mail' try: send_email( "Welcome to %s. You successfully registered" % 'RoseGuarden', config.MAIL_USERNAME, [user.email], render_template("welcome_mail.txt", user=user), render_template("welcome_mail.html", user=user)) except: print 'unable to send mail' return '', 201 return '', 201
def post(self, id): if g.user.role != 1: return make_response(jsonify({'error': 'Not authorized'}), 403) form = SettingPatchForm() if not form.validate_on_submit(): print form.errors return form.errors, 422 setting = Setting.query.filter_by(id=id, name=form.name.data).first() if setting is None: return '', 405 logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, "Changed setting " + str(setting.name) + " from " + str(setting.value) + " to " + str(form.value.data), 'Changed setting', 'L2', 0, 'Web based') db.session.add(logentry) db.session.commit() settings.setOrUpdateSettingValue(form.name.data, int(form.type.data), form.value.data) return '', 201
def post(self, id): if g.user.id != id: if g.user.role != 1: return '', 401 user = User.query.filter_by(id=id).first() if user is None: return '', 401 user.cardID = "" logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'Invalidate auth. card of ' + user.firstName + ' ' + user.lastName + ' (' + user.email + ')', 'Invalidate auth. card', 'L2', 0, 'Web based', Action.ACTION_LOGONLY) try: db.session.add(logentry) db.session.commit() except: db.session.rollback() return '', 401 return '', 201
def api_change_admin_role(): current_admin = Admin.query.filter_by(email=session['user']).first() if current_admin.role != 'full': return abort(403) role = request.args.get('role') if role not in ['full', 'normal', 'observer']: raise ValueError("Invalid Role") id = request.args.get('id') admin = Admin.query.filter_by(id=id).first() old_role = admin.role admin.role = role action = Action(owner=current_admin.id, type='changeadminrole', target_type='admin', text="Changed {0}'s admin role ({1} -> {2})".format(admin.name, old_role, role), target_id=admin.id) db.session.add(action) db.session.commit() return jsonify(status="OK")
def post(self): print 'RFID withdraw request received' # check request paremeters (form) form = RFIDTagAssignForm() if not form.validate_on_submit(): return form.errors, 422 # check admin rights if g.user.role != 1: return make_response(jsonify({'error': 'Not authorized'}), 403) user = User.query.filter_by(email=form.email.data).first() if (user == None): return make_response(jsonify({'error': 'user not found'}), 400) if form.rfidTagId.data is not None and form.rfidTagId.data != '': if not backgroundWorker.withdrawRFIDTag(user): print 'Error while withdraw cardID ' + user.cardID + ' from ' + user.firstName + ' ' + user.lastName db.session.rollback() return make_response(jsonify({'error': 'user not found'}), 400) else: user.cardID = '' user.cardSecret = '' user.cardAuthKeyA = '' user.cardAuthKeyB = '' db.session.commit() print 'Withdraw cardID ' + form.rfidTagId.data + ' from ' + user.firstName + ' ' + user.lastName logentry = Action( datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'Withdraw cardID-tag ' + form.rfidTagId.data + ' from ' + user.firstName + ' ' + user.lastName, 'Card administration', 'L2', 0, 'Web based') db.session.add(logentry) db.session.commit() return '', 201 else: return make_response(jsonify({'error': 'bad request data'}), 400)
def api_bulk_invite(): if 'file' not in request.files: return abort(403) file = request.files['file'] from io import StringIO csvf = StringIO(file.read().decode()) reader = csv.DictReader(csvf, delimiter=',') current_user = Admin.query.filter_by(email=session['user']).first() for line in reader: token = str(uuid.uuid4()) user = User(line['E-mail 1 - Value'], token) db.session.add(user) action = Action( owner=current_user.id, type='inviteuser', target_type='user', text='Invited user ({0})'.format( user.email), target_id=user.id) db.session.add(action) db.session.commit() utils.send_invite(user, line['Given Name']) return jsonify(status="OK")