def login(conn, data): """Handle client request login and handle multiple failures. Args: conn (socket.socket): socket connected to client. data (string): data in packet received. """ data = eval(data) username = data["username"] password = data["password"] users = get_users() if username not in users.keys(): pk = packet(MessageType.login_fail, "User not exist.") msg = pk.to_message() conn.send(msg) return if users[username] != password: pk = packet(MessageType.login_fail, "Password incorrect.") msg = pk.to_message() conn.send(msg) return pk = packet(MessageType.login_success, "") msg = pk.to_message() conn.send(msg) print("[LOGIN] Login successful") return
def get_all_task(request): """ 获取所有任务 :param request: :return: """ try: tasks = Task.objects.get_all_task() except Exception as e: logger.error(u"获取任务失败", e) return render_json({'result': False, 'message': u"获取任务失败"}) users = get_users(request) data = [] for task in tasks: # 获取用户名 participant = task.participant.split(',') user_name = [] for id in participant: user = users[int(id)] user_name.append(user['name']) data.append({ 'task_name': task.name, 'task_introduction': task.introduction, 'task_participant': user_name, 'task_create_time': task.create_time.strftime('%Y-%m-%d'), 'task_finish_time': task.finish_time.strftime('%Y-%m-%d'), 'task_status': STATUS_CHOICES[int(task.status)], 'level': LEVEL[int(task.level)], }) return render_json({'result': True, 'data': data})
def _auth(username, timestamp, hexdigest): """ 身份验证 @username: 用户名 @timestamp: 时间戳 @hexdigest: 摘要 """ timestamp2date = datetime.datetime.fromtimestamp(int(timestamp)) now_date = datetime.datetime.now() interval = now_date - timestamp2date # 校验时间戳 if abs(interval.total_seconds()) > TIMESTAMP_AVAI: return False # 校验用户 users = get_users() if not users.has_key(username): return False password = users.get(username) data = {'X-Timestamp': int(timestamp), 'X-Username': username} message = urllib.urlencode(data) vhmac = hmac.new(password) vhmac.update(message) vhexdigest = vhmac.hexdigest() if vhexdigest != hexdigest: return False return True
def __init__(self, parent=None): super(add_user_dialog, self).__init__(parent) self.setGeometry(10, 30, 300, 200) # Left, top, width, height. self.label = QtGui.QLabel( """You must create an account linked to an email that you frequently check. The homecage system will send you daily updated about your subjects which MUST be checked to ensure there are no welfare concerns. Therefore we will do an email confirmation thing to register """) self.textName = QtGui.QLineEdit("User Name") self.textEmail = QtGui.QLineEdit("User email") self.addUserButton = QtGui.QPushButton('Send code', self) self.addUserButton.clicked.connect(self.send_code) self.confirm_email = QtGui.QLineEdit("Enter code") self.confirmCodeButton = QtGui.QPushButton('Confirm', self) self.confirmCodeButton.clicked.connect(self.handleLogin) #self.addUserButton.clicked.connect(self.handleLogin) self.users = get_users() layout = QtGui.QVBoxLayout(self) hlayout = QtGui.QHBoxLayout() hlayout.addWidget(self.textName) hlayout.addWidget(self.textEmail) hlayout.addWidget(self.addUserButton) hlayout2 = QtGui.QHBoxLayout(self) hlayout2.addWidget(self.confirm_email) hlayout2.addWidget(self.confirmCodeButton) layout.addWidget(self.label) layout.addLayout(hlayout) layout.addLayout(hlayout2)
def send_email(send_message, subject, receiver_email, opening=None): """ This function actually send an email""" lines_ = open(user_path, 'r').readlines() users = get_users() sender_email = [ re.findall('"(.*)"', l)[0] for l in lines_ if "system_email" in l ][0] password = [re.findall('"(.*)"', l)[0] for l in lines_ if "password" in l][0] message = MIMEMultipart("alternative") message["Subject"] = "Pyhomecage 24h summary" message["From"] = sender_email message["To"] = receiver_email if opening is None: opening = """\ This is an automated message from pycontrol about the status of your mice. """ # Turn these into plain/html MIMEText objects part1 = MIMEText(opening, "plain") # Add HTML/plain-text parts to MIMEMultipart message # The email client will try to render the last part first message.attach(part1) message.attach(send_message) context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string()) return None
def _auth(username, timestamp, hexdigest): """ 身份验证 @username: 用户名 @timestamp: 时间戳 @hexdigest: 摘要 """ timestamp2date = datetime.datetime.fromtimestamp(int(timestamp)) now_date = datetime.datetime.now() interval = now_date - timestamp2date # 校验时间戳 if interval.seconds<0 or interval.seconds>TIMESTAMP_AVAI: return False # 校验用户 users = get_users() if not users.has_key(username): return False password = users.get(username) data = { 'X-Timestamp':int(timestamp), 'X-Username':username } message = urllib.urlencode(data) vhmac = hmac.new(password) vhmac.update(message) vhexdigest = vhmac.hexdigest() if vhexdigest != hexdigest: return False return True
def index(): token = session['vk_token'] user_id = session['vk_user_id'] user = get_users(token, [user_id])[0] friends = get_five_random_friends(token, user_id) data = {'user': user, 'friends': friends} return render_template('index.html', data=data)
def handleLogin(self): self.users = get_users() if str(self.confirm_email.text()) == str(self.code): ###FIX TO IGNORE CASE #####!!!!!!!!!!!!!!!!! if self.user.lower() not in [i.lower() for i in self.users]: with open(user_path, 'a') as file: user_details = "user_data:{'" + str( self.user) + "':' " + str(self.receiver_email) + "'}" file.writelines('\n' + user_details) self.accept()
def search_project(request): """ 搜索项目 :param request: :return: """ pro_name = request.GET.get('pro_name', '') part_projects_res = Project.objects.get_user_part_project(request=request) owner_projects_res = Project.objects.get_user_owner_project( request=request) # 获取所用用户信息 users = get_users(request) # 获取拥有的项目 owner_project = [] for project in owner_projects_res: if pro_name in project.name or pro_name == '': pid = project.pk name = project.name logo = project.logo intro = project.introduction avatar = request.session['avatar'] owner_project.append({ 'pid': pid, 'name': name, 'logo': logo, 'intro': intro, 'avatar': avatar, 'owner': request.session['name'] }) # 获取参与的项目 part_project = [] for project in part_projects_res: if pro_name in project.name or pro_name == '': pid = project.pk name = project.name logo = project.logo intro = project.introduction owner = project.owner user = users[int(owner)] avatar = user['avatar'] owner = user['name'] part_project.append({ 'pid': pid, 'name': name, 'logo': logo, 'intro': intro, 'avatar': avatar, 'owner': owner }) return render(request, 'index.html', { 'owner_project': owner_project, 'part_project': part_project })
def users(): if utils.needs_user(): return flask.redirect(flask.url_for('setup')) if ('logged_in' not in flask.session) or (not flask.session['logged_in']): return flask.redirect(flask.url_for('login')) error = None if flask.request.method == 'POST': if "delete" in flask.request.form: if len(utils.get_users()) > 1: user_id = int(flask.request.form['id']) utils.delete_user(user_id) flask.flash('User Deleted') else: flask.flash("can not delete last user") else: username = flask.request.form['username'] user = utils.get_user(username) if (not user) or ("edit" in flask.request.form): password = flask.request.form['password'] password_confirm = flask.request.form['password_confirm'] if password == password_confirm: if "edit" in flask.request.form: user_id = int(flask.request.form['edit']) utils.modify_user(user_id, username, password) flask.flash('User Edited') else: utils.create_user(username, password) flask.flash('User Created') if "setup" in flask.request.form: return flask.redirect(flask.url_for('login')) else: error = "passwords do not match" else: error = "user already exists" users = utils.get_users() return flask.render_template( 'users.j2', users=users, error=error)
def get_all_user(request): """ 获取出当前用户外所有用户 :param request: :return: """ user_info = get_users(request) user_list = [] for id, user in user_info.items(): user_list.append({'id': id, 'text': user['name']}) return render_json({'result': True, 'message': user_list})
def messages_script(): chat_id = 100 nmessages = 3000 messages = utils.get_messages(api, chat_id=chat_id, nmessages=nmessages) msg_stats, = utils.data_to_dict( handler_list=[handlers.user_messages_count], data=messages) users = utils.get_chat_users(api, chat_id) utils.get_users(api, user_ids=msg_stats, user_dict=users) names = utils.get_full_names(users) views.dict_view(view_method=views.plotly_hist, keys=sorted(list(msg_stats.keys()), key=lambda item: msg_stats[item]), label_dict=names, data_dict=msg_stats, rate=False)
def users(): if utils.needs_user(): return flask.redirect(flask.url_for('setup')) if ('logged_in' not in flask.session) or (not flask.session['logged_in']): return flask.redirect(flask.url_for('login')) error = None if flask.request.method == 'POST': if "delete" in flask.request.form: if len(utils.get_users()) > 1: user_id = int(flask.request.form['id']) utils.delete_user(user_id) flask.flash('User Deleted') else: flask.flash("can not delete last user") else: username = flask.request.form['username'] user = utils.get_user(username) if (not user) or ("edit" in flask.request.form): password = flask.request.form['password'] password_confirm = flask.request.form['password_confirm'] if password == password_confirm: if "edit" in flask.request.form: user_id = int(flask.request.form['edit']) utils.modify_user(user_id, username, password) flask.flash('User Edited') else: utils.create_user(username, password) flask.flash('User Created') if "setup" in flask.request.form: return flask.redirect(flask.url_for('login')) else: error = "passwords do not match" else: error = "user already exists" users = utils.get_users() return flask.render_template('users.j2', users=users, error=error)
def filter_stage(options): """Filter accounts in the first stage into mid-approval.""" # Process all of the recently requested accounts with fancy_open(options.users_file, lock = True, pass_missing = True) as f: needs_approval = filter_accounts(get_users(f, options), options) for user, comment in needs_approval: msg = "`{}` ({}) needs approval: {}".format(user['account_name'], user['owner'], comment) write_and_alert('/srv/atool/pending', msg, all=True) # Write the users needing staff approval back to the users file with fancy_open(options.users_file, "w", lock = True) as f: write_users(f, [user for user, comment in needs_approval])
def __init__(self, parent=None): super(login_dialog, self).__init__(parent) self.setGeometry(10, 30, 300, 200) # Left, top, width, height. self.userID = None self.buttonLogin = QtGui.QPushButton('Login', self) self.buttonLogin.clicked.connect(self.handleLogin) self.combo = QtGui.QComboBox() self.users = get_users() self.combo.addItems(['Select User'] + self.users) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.combo)
def all_users(): # if request.method == "POST": # if search == "none": users_list = get_all_users() page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='per_page') total = len(users_list) pagination_users = get_users(offset=offset, per_page=per_page) pagination = Pagination(page=page, per_page=per_page, total=total, css_framework='bootstrap4') return render_template('users.html', title=title, user_list=pagination_users, page=page, per_page=per_page, pagination=pagination, change_offset=get_users, )
def fromPHID(phid): if phid in phid_cache: return phid_cache[phid] raw = utils.get_users([phid]) if(len(raw) > 0): return User(raw[0]) user = User(None) user.phid = phid user.username = phid user.name = phid if "PHID-APPS" in phid: user.name = "Phabricator" user.username = "******" return user
async def authenticate(request): username = request.json.get("username", None) password = request.json.get("password", None) if not username or not password: raise exceptions.AuthenticationFailed("Missing username or password.") username_table = get_users() user = username_table.get(username, None) if user is None: raise exceptions.AuthenticationFailed("User not found.") if password != user.password: raise exceptions.AuthenticationFailed("Password is incorrect.") return user
def sms(): # NOTE: This uses our makeshift version of a database (a lame csv). One should # consider improving. response = ElementTree.Element('Response') message = ElementTree.SubElement(response, 'Message') sender = request.form['From'][2:] command = request.form['Body'].upper() users = get_users() numbers = [user[3] for user in users] if not (sender in numbers): message.text = 'Sorry, you are using an unidentified number.' else: user = next((_ for _ in users if _[3]==sender), None) if user[4] != 'True': message.text = 'This agent has been eliminated. Contact GM for help.' elif command == 'DEAD': message.text = 'Thanks for playing! Hope you had fun.' kill_user(users.index(user)) assassin = assassin_of(users.index(user)) bounty = ElementTree.SubElement(response, 'Message', attrib={'to':assassin[3]}) bounty.text = ('Agent %s has been eliminated. Your new target is %s.' ' Good luck.' % (user[0], user_target(users.index(assassin))[0])) elif command == 'COMPLETE': target = user_target(users.index(user)) kill_user(users.index(target)) message.text = ('Congratulations. Your next target is %s. Good luck.' % user_target(users.index(user))[0]) obituary = ElementTree.SubElement(response, 'Message', attrib={'to':target[3]}) obituary.text = ('Sources state you have been eliminated by %s. ' 'Thanks for playing!') % user[0] elif command == 'HELP': message.text = 'Available commands: DEAD, COMPLETE.' else: message.text = ('This is an automated system. Unrecognized command. ' 'HELP for help.') response = ElementTree.tostring(response) response = make_response(response) response.headers['Content-Type'] = 'application/xml' return response
def create_stage(options): """Create accounts in the mid-approval stage.""" try: principal = options.admin_user + "/admin" if getattr(options, "keytab", None) is None: # Autheticate our ldap session using gssapi options.admin_password = \ getpass("{0}@OCF.BERKELEY.EDU's Password: "******"", ldap.sasl.gssapi("")) with fancy_open(options.mid_approve, lock = True, pass_missing = True, delete = True) as f: finalize_accounts(get_users(f, options), options) finally: check_call(["kdestroy"])
def load_users_and_groups(): user_names = defaultdict(list) get_rooms_output = utils.get_rooms(developer_tokens['charu']) for room in get_rooms_output['items']: curr_id = room['id'] users_in_room = utils.get_users(developer_tokens['charu'], curr_id) for users in users_in_room: first_name = (users[0].split())[0] if first_name in user_names: already_exists = False for same_first_name in user_names[first_name]: if same_first_name[1] == users[1]: already_exists = True break if not already_exists: user_names[first_name].append(users) else: user_names[first_name].append(users) with open('suggested_users.json', 'w') as fp: json.dump(user_names, fp, sort_keys=True, indent=4)
def load_users_and_groups(): user_names = defaultdict(list) get_rooms_output =utils.get_rooms(developer_tokens['charu']) for room in get_rooms_output['items']: curr_id = room['id'] users_in_room = utils.get_users(developer_tokens['charu'], curr_id) for users in users_in_room: first_name = (users[0].split())[0] if first_name in user_names: already_exists = False for same_first_name in user_names[first_name]: if same_first_name[1] == users[1]: already_exists = True break if not already_exists: user_names[first_name].append(users) else: user_names[first_name].append(users) with open('suggested_users.json', 'w') as fp: json.dump(user_names, fp, sort_keys=True, indent=4)
def __init__(self, parent=None): super(are_you_sure_dialog, self).__init__(parent) self.setGeometry(10, 30, 300, 100) # Left, top, width, height. self.buttonLayout = QtGui.QHBoxLayout() self.yesButton = QtGui.QPushButton('Yes', self) self.noButton = QtGui.QPushButton('No', self) self.buttonLayout.addWidget(self.noButton) self.buttonLayout.addWidget(self.yesButton) self.yesButton.clicked.connect(self.handleYes) self.noButton.clicked.connect(self.handleNo) self.users = get_users() self.Question = QtGui.QLabel() self.Question.setText("Are you sure?") layoutV = QtGui.QVBoxLayout(self) layoutV.addWidget(self.Question) layoutV.addLayout(self.buttonLayout)
codes[dp][pj] = [] codes[dp][pj].append(sp) subject = 'Engineering Spare Parts QTY Alarm' author = (('QTY Alarm', '*****@*****.**')) line = '~' * 60 remark = 'This notification will be sent out from Monday to Friday' no_leader = '''<h1><font color="red"> No project leader specified for:</font></h1><br />''' css = dict(td_style=mt.td_style) for dp, projects in codes.items(): for pj, sps in projects.items(): groups = utils.get_groups(db, dp, pj, role='project_leader') to_list = utils.get_users(db, groups, can_send='alarm') body = [] if not to_list: groups = utils.get_groups(db, dp, pj, role='asset_leader') to_list = utils.get_users(db, groups) body.append(no_leader) body.append(mt.header.format(header=subject, department=dp, project=pj, ) ) body.append(mt.table_header.format(table_style=mt.table_style, thead_style=mt.thead_style, tr_style=mt.tr_style, td_style=mt.td_style,
from raw_records WHERE latitude > {0} AND latitude < {1} AND longitude > {2} AND longitude < {3}; """.format( config.BOUNDS['south'], config.BOUNDS['north'], config.BOUNDS['west'], config.BOUNDS['east'], )) from schema import RecordsOnOneDay logger.info("Preloading RecentUserRecord object") users = get_users(session) records = session.query(RecordsOnOneDay).order_by( RecordsOnOneDay.c.timestamp) date_dummy = date.today() dayusers = [] with progressbar.ProgressBar(max_value=len(users)) as progress: for i, u in enumerate(users): logger.info("Calculating the user's centroid of movement") centroid_of_movement = session.query( func.avg(RecordsOnOneDay.c.lat).label('lat'), func.avg(RecordsOnOneDay.c.long).label('long'), ).filter(RecordsOnOneDay.c.new_user_id == u).first() count = records.filter(RecordsOnOneDay.c.new_user_id == u).count()
body_title = '<h1>There are {} incomings:</h1>' no_leader = '<h1>But no project leader is specified.</h1>' line = '~' * 60 dept_fmt = '» Department: <strong>{}</strong><br />' proj_fmt = '» Project: <strong>{}</strong><br />' url = '''More details on <a href='http://{ip}/buys/?routing=fresh'> http://{ip}/buys/?routing=fresh</a> or <a href='http://teasset/buys/?routing=fresh'> http://teasset/buys/?routing=fresh</a>. '''.format(ip=utils.get_ip()) remark = '''This notification will be sent out from Monday to Friday''' for dept, projects in users.items(): for proj, num in projects.items(): groups = utils.get_groups(db, dept, proj) to_list = utils.get_users(db, groups, can_send='notify') body = [body_title.format(num)] body.append(dept_fmt.format(dept)) body.append(proj_fmt.format(proj)) if to_list: body.append(url) else: body.append(no_leader) groups = utils.get_groups(db, dept, proj, role='asset_leader') to_list = utils.get_users(db, groups) body.append('<br />') body.append(line) body.append(remark) send_mail(subject=subject, body='<br />'.join(body),
for mouseID in mouse_IDs: last_seen = datetime.strptime( mouse_dict[mouseID+'__last_seen'],'%Y-%m-%d-%H%M%S') rows.append({'MouseID': mouseID, 'Baseline': mouse_dict[mouseID+'__baseline'], 'Current_weight': mouse_dict[mouseID+'__now_weight'], 'frac_baseline': mouse_dict[mouseID+'__frac_baseline'], 'last_seen': mouse_dict[mouseID+'__last_seen'], 'hours_since_last_visit': np.round((datetime.now()-last_seen).total_seconds()/3600.,decimals=1)}) df = pd.DataFrame.from_dict(rows, orient='columns') message = MIMEText(df.to_html(), "html") send_email(message,subject='Daily Update',receiver_email=receiver_email) #send_email(message,subject='Daily Update',receiver_email="*****@*****.**") if __name__=='__main__': daemon_start_time = datetime.now() users = get_users(); user_dicts = get_user_dicts() ROOT,task_dir,experiment_dir,setup_dir,mice_dir,data_dir,AC_logger_dir,protocol_dir = all_paths last_check = datetime.now() -timedelta(seconds=20) warning_checkDict = {} for u in users: if u not in warning_checkDict.keys(): warning_checkDict[u] = datetime.now() - timedelta(days=1) last_regular_update = datetime.now() - timedelta(days=2) last_post = datetime.now() - timedelta(days=2) _,error_log_on_startup = check_GUI_error_log(setup_dir) while True: now = datetime.now() #print(now,last_check) if abs((now-last_check)).total_seconds()>10:
def get_table(): req = request.args users = get_users(dm, req) return render_template("table.html", users=users)
no_leader_title = '''<h1><font color="red"> But no asset user is specified.</font></h1>''' line = '~' * 60 dept_fmt = '» Department: <strong>{}</strong><br />' proj_fmt = '» Project: <strong>{}</strong>' url = '''More details on <a href='http://{ip}/buys/?routing=accept'> http://{ip}/buys/?routing=accept</a> or <a href='http://teasset/buys/?routing=accept'> http://teasset/buys/?routing=accept</a>. '''.format(ip=utils.get_ip()) remark = '''This notification will be sent out from Monday to Friday''' for dept, projects in users.items(): for proj, num in projects.items(): groups = utils.get_groups(db, dept, proj, role='asset_user') to_list = utils.get_users(db, groups) body = [body_title.format(num)] if to_list: body.append(url) else: body.append(no_leader_title) groups = utils.get_groups(db, dept, proj, role='asset_leader') to_list = utils.get_users(db, groups) body.append(dept_fmt.format(dept)) body.append(proj_fmt.format(proj)) body.append('<br />') body.append(line) body.append(remark) send_mail(subject=subject, body='<br />'.join(body),
import smtplib, ssl import re from loc_def import user_path, all_paths from utils import get_users from datetime import date, timedelta from datetime import datetime import pandas as pd import json import os from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from utils import get_users, get_user_dicts lines_ = open(user_path, 'r').readlines() users = get_users() sender_email = [ re.findall('"(.*)"', l)[0] for l in lines_ if "system_email" in l ][0] password = [re.findall('"(.*)"', l)[0] for l in lines_ if "password" in l][0] port = 587 # For starttls smtp_server = "smtp.gmail.com" message = MIMEMultipart("alternative") message["Subject"] = "Pyhomecage 24h summary" message["From"] = sender_email message["To"] = receiver_email def get_weight_history(logger_path):