def api_get_users(): total = User.count_all() page = Page(total, _get_page_index()) users = User.find_by(order='created_at desc', offset=page.offset, limit=page.limit) for u in users: u.password = '******' return dict(users=users, page=page)
def register(): name = request.form.get("name") email = request.form.get("email") password = request.form.get("password") hashed_pwd = hashlib.sha256(password.encode()).hexdigest() secret_number = random.randint(1, 30) games = 0 wins = 0 losses = 0 score = 0 user = db.query(User).filter_by(name=name).first() if name and email and password: if not user: user = User( name=name, email=email, password=hashed_pwd, secret_number=secret_number, games=games, wins=wins, losses=losses, score=score, online=True, offline=False, ) session_token = str(uuid4()) user.session_token = session_token db.add(user) db.commit() response = make_response(redirect(url_for("home"))) response.set_cookie( "session_token", session_token, ) return response else: flash(f"Please fill all data to complete registration") return render_template("register.html", user=user)
def delete_user(): _id = request.args.get('id') _user,_error = User.get_info(_id=_id) if _user is None: _error = '用户信息不存在' else: username = _user[0]['username'] _session_username = session['user']['username'] if User.check_is_admin(_session_username): User.delete_user(_id) flash("%s删除成功" %username) else: flash('权限不够,只有管理员才能删除用户信息!') return redirect('/users/')
def authorize(): if request.method == 'GET': if request.args.get('client_id') == 'supermenu': return render_template('login.html', authorize=True) elif request.method == 'POST': username = request.form.get('username') password = request.form.get('password') user = User(username, db) if user.verify_password(password): user_code = user.get_id() state = request.args.get('state') redirect_url = unquote(request.args.get('redirect_uri')) redirect_url += '&code={}&state={}&response_type=code'.format(user_code, state) return redirect(redirect_url)
def scan_for_events(self): """ Method for scanning database for new events on an interval. """ # Load current date and time in correct format current_datetime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] while True: # Read latest datetime from file. If not present, write. try: with open('datetime.json', 'r+') as file: data = json.load(file) current_datetime = data['current_datetime'] except (FileNotFoundError, json.decoder.JSONDecodeError): with open('datetime.json', 'w+') as file: file.write(json.dumps({'current_datetime': current_datetime})) # Get and handle events. events = self.db.get_event_details(current_datetime) for event in events: if not event['severity'] == 1: continue username = None login_name = event['login_name'] email = event['email'] user_to_handle = '' if username: user_to_handle = username.split('\\')[1] if '\\' in username else username elif login_name: user_to_handle = login_name.split('\\')[1] if '\\' in login_name else login_name elif email: user_to_handle = email.split('@')[0] else: print('No username could be sourced from this event \'%s\'.' % event['event_id']) continue with open('datetime.json', 'w+') as file: file.write(json.dumps({'current_datetime': event['insert_date'].strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]})) user = User(user_to_handle) user.handle() time.sleep(10)
def createUser(login_session): newUser = User(name=login_session['username'], email=login_session['email']) session.add(newUser) session.commit() user = session.query(User).filter_by(email=login_session['email']).one() return user.id
def new_user(): name = request.json.get('username').lower() password = request.json.get('password') email = request.json.get('email').lower() if name is None or password is None or email is None: return (jsonify({'data': 'Missing values', 'error': '400'}), 400) existing_email = session.query(User).filter_by(email=email).first() if existing_email is not None: return (jsonify({'data': 'user already exists'}), 200) user = User(name=name, email=email) user.hash_password(password) session.add(user) session.commit() return (jsonify({'data': 'user created successfully'}), 200)
def login(): name = request.form.get("name") password = request.form.get("password") hashed_pwd = hashlib.sha256(password.encode()).hexdigest() user = db.query(User).filter_by(name=name).first() if not user: flash(f"User doesn't exists. Please register.") return redirect(url_for("reg")) if hashed_pwd != user.password: flash(f"Wrong user name, email or password. Try again please.") return redirect(url_for("home")) else: session_token = str(uuid4()) user.session_token = session_token user = User(online=True, offline=False) db.add(user) db.commit() response = make_response(redirect(url_for("home"))) response.set_cookie("session_token", session_token) return response
def finder_user(): username = request.form.get('username','') users,_error = User.get_info(username=username) if users: return render_template('users.html',users = users) flash("Sorry,没有查到相关数据!") return render_template('users.html')
def exec_cmd(): _cmds = [] _rrt = {} port=21860 center = Center() _id = request.form.get('serverid', '') _ip = request.form.get('serverip', '') print "id is %s,ip is %s" %(_id,_ip) _user_manage_passwd = request.form.get('manage-passwd','') _cmd = request.form.get('cmd','') print _cmd for x in _cmd.split(';'): _cmds.append(x) print _cmds print "cmds is %s,passwd is %s" %(_cmds,_user_manage_passwd) _rt = User.validate_login('admin',_user_manage_passwd) if _rt: #_result,_error = Remote_cmd.ssh_execute(_ip,'root','1meWsgvYeSjMA0pecBMg',port,_cmds) _result = center.request(str(_cmds)) for r in _result: if not r[2]: if len(r[1]) > 0: _rrt[r[0]] = r[1] else: _rrt[r[0]] = r[2] else: if not _error: return json.dumps({'is_ok':'true', 'error':'', 'success':'true','result':_result}) return json.dumps({'is_ok':'false', 'error':'', 'success':'false','result':'执行失败,请您确认已正确输入管理员密码和命令行!'})
def load_user(user_id): logger.debug(user_id) mongo_users = mongoCollection('users') user_info = mongo_users.find_one( {'_id': ObjectId(user_id.decode('utf-8'))}) logger.debug(user_info) return User(user_info)
def modify_password(): _id = session.get('user').get('id') print "id is %s" %_id _users,_error = User.get_info(_id=_id) if _users: _username = _users[0]['username'] _password =_users[0]['password'] _age = _users[0]['age'] return render_template('passwd_modify.html',username=_username)
def modify_user(): _id = request.args.get('id', '') _users,_error = User.get_info(_id=_id) if _users: _username = _users[0]['username'] _password =_users[0]['password'] _age = _users[0]['age'] else: _error = '用户不存在' return render_template('user_modify.html',_error=_error,_id=_id,password=_password, age=_age, username=_username)
def update_user(): #获取修改页面的用户信息 _id = request.form.get('id', '') username = request.form.get('username', '') password = request.form.get('password', '') age = request.form.get('age', 0) _session_id = session['user']['id'] _session_username = session['user']['username'] #print type(_id),type(_session_id) #print type(_id),type(username),type(password),type(age) #检查在修改页面的用户信息 _is_ok, _error = User.validate_update_user(_id,_session_id,username,_session_username,password,age) #print "valid:%s" %_is_valid_ok #print "error:%s" %_error if _is_ok: User.update_user(_id,username, password, age) # flash("用户%s修改成功!" %username) # return redirect('/users/') return json.dumps({'is_ok':_is_ok, "error":_error})
def custom_logs(): sql = request.form.get('sql','select * from logs limit 10;') print "sql is %s" %sql _result,_error = User.get_info(_sql=sql) if not sql: return redirect('/user/customlogs/') if _result: return render_template("customlogs.html",result=_result,sql=sql) else: return render_template("customlogs.html",result=_result,sql=sql,error=_error)
def register_user(): i = ctx.request.input(name='', email='', password='') name = i.name.strip() email = i.email.strip() password = i.password if not name: raise APIValueError('name') if not email or not _RE_EMAIL.match(email): raise APIValueError('email') if not password and not _RE_MD5.match(password): raise APIValueError('password') user = User.find_first(email=email) if user: raise APIError('register:failed', 'email', 'Email is already registed.') user = User(name=name, email=email, password=password, image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email).hexdigest()) user.insert() cookie = make_signed_cookie(user.id, user.password, None) ctx.response.set_cookie(_COOKIE_NAME, cookie) return user
def verify_password(username_or_token, password): user_id = User.verify_auth_token(username_or_token) if user_id: user = session.query(User).filter_by(id=user_id).first() if not user: return False else: user = session.query(User).filter_by(name=username_or_token).first() if not user or not user.verify_password(password): return False g.user = user return True
def get(self): result = {"status": False} try: users = User().query() result["message"] = self.render_string("admin/user_manage.html", users=users) result["status"] = True except Exception as e: print e result["message"] = "用户管理请求错误" self.write(json.dumps(result)) self.finish()
def update_passwd(): _id = session.get('user').get('id') #提交表单中的原密码 _password = request.form.get('_password') print "old passwd :%s" %_password #提交表单中的新密码 _password1 = request.form.get('_password1') _password2 = request.form.get('_password2') print "new passwd1:%s" %_password1 print "new passwd2:%s" %_password2 _result,_error = User.validate_new_password(_id,_password1,_password2) if User.validate_password(_id,_password): if _result: User.update_password(_id,_password1) flash("密码修改成功!") return redirect('/users/') else: return render_template('passwd_modify.html',error=_error,_password=_password,_password1=_password1,_password2=_password2) else: flash("原密码输入错误,请重新输入!") return render_template('passwd_modify.html')
def add_user(): if login_session['type'] != 'ADMIN': flash('You Not Authorized To Access This Page') return redirect(url_for('index')) form = RegisterForm(request.form) print 'this is user ID :LPL' if request.method == "POST": if form.validate_on_submit(): print 'this is user ID :' username = session.query(User) \ .filter(User.username == form.username.data).one_or_none() if username: flash('The username Used Before') return redirect(request.url) user_email = session.query(User) \ .filter(User.email == form.email.data).one_or_none() if user_email: flash('This Email Used Before') return redirect(request.url) # all Ok saving User user = User(name=form.name.data, email=form.email.data, username=form.username.data, type=form.type.data) user.hash_password(form.password.data) session.add(user) session.flush() if request.files['file']: filename = save_file(request.files['file'], str(user.id)) if filename: # Check if the photo is saved or not user.picture = u'users/' + filename else: # error in saving the photo flash("This Isn't an Image") return redirect(request.url) else: session.commit() flash("Employee %s Added Successfully" % user.name) return redirect(url_for('index')) return render_template('addUser.html', form=form)
def delete_asset(): _id = request.args.get('id') _asset,_error = Assets.get_by_id(_id=_id) if not _asset: _error = '资产不存在' else: _session_username = session['user']['username'] if User.check_is_admin(_session_username): Assets.delete(_id) flash("删除成功") else: flash('权限不够,只有管理员才能删除资产信息!') return redirect('/asserts/')
def login(): if request.method == 'GET': return render_template('login.html', login=True) username = request.form.get('username') password = request.form.get('password') action = request.form.get('button') if action == 'toregister': return redirect(url_for('register')) if not username: flash('请填写用户名') return render_template('login.html') elif not password: flash('请填写密码') return render_template('login.html') user = User(username, db) if user.verify_password(password): login_user(user) return redirect(url_for('index')) else: flash('用户名或密码无效') return render_template('login.html')
def scan_for_message(self): """ Method for running a kafka bus scan. Polls for new messages and upon receiving one, if the user risk level is 4/5 it handles the user. """ while True: msg = self.consumer.poll(0.1) if msg is None: continue elif not msg.error(): message = json.loads(msg.value().decode('utf8')) print('Received message: {0}'.format(message)) if message['risk_level'] >= 4: user = User(message['user_id'].replace(' ', '.')) user.handle() elif msg.error().code() == KafkaError._PARTITION_EOF: print('End of partition reached {0}/{1}'.format( msg.topic(), msg.partition())) else: print('Error occured: {0}'.format(msg.error().str()))
def delete(self): result = {"status": False} try: uid = self.get_argument("uid") if not self.number.search(uid): lastrowid = User().delete(uid) result["message"] = "删除成功" result["status"] = True else: result["message"] = "UID错误" except Exception as e: print e result["message"] = "删除用户异常" self.write(json.dumps(result)) self.finish()
def api_authenticate(): i = ctx.request.input(remember='') email = i.email.strip().lower() password = i.password remember = i.remember user = User.find_first(email=email) if user is None: raise APIError('auth:failed', 'email', 'Invalid email.') elif password != user.password: raise APIError('auth:failed', 'password', 'Invalid password.') max_age = 604800 if remember == 'true' else None cookie = make_signed_cookie(user.id, user.password, max_age) ctx.response.set_cookie(_COOKIE_NAME, cookie, max_age=max_age) user.password = '******' return user
def register(): if request.method == 'GET': return render_template('register.html') elif request.method == 'POST': name = request.form.get('name', None) user_list = User.query.filter(User.name==name).all() if user_list: return render_template('register.html', register_info='<div class="alert alert-danger" role="alert">账号已存在</div>') else: password = request.form.get('password', None) password = hashlib.sha1(password).hexdigest() user = User(name=name, password=password) db.session(user) db.session.commit() return redirect(url_for('index'))
def user_add(): form = UserForm() # print(form.__dict__) # 判断表单是否通过 try: if form.validate_on_submit(): user = User(form.username.data, form.password.data, form.is_valid.data) db.session.add(user) db.session.commit() flash('添加成功!') return redirect(url_for('admin.manager_user')) except: flash('你输入的用户名已存在!', category='error') return render_template('admin/user_add.html', form=form)
def parse_signed_cookie(cookie_str): try: L = cookie_str.split('-') if len(L) != 3: return None id, expires, md5 = L if int(expires) < time.time(): return None user = User.get(id) if user is None: return None if md5 != hashlib.md5('%s-%s-%s-%s' % (id, user.password, expires, _COOKIE_KEY)).hexdigest(): return None return user except: return None
def create_user_util(user): try: if user["password"] == None : return Response('Invalid input, not all fields present', 400) user = User(**user) except: return Response('Invalid input, not all fields present', 400) if check_if_user_exists_by_username_util(user.user_name): return Response("User with this username already exist, username should be unique", 400) session.add(user) session.commit() return Response("Created", 201)
def upload_action(): img = request.files.get('img') if img: #_file_name = img.filename _file_name = img.filename _file_path = './users/static/images/%s' %_file_name _up_ok,_path =User.upload_validate_check(_file_path) _path = 'static/images/'+os.path.basename(_path) print _path if _up_ok: img.save(_file_path) return render_template('upload_action.html',_path=_path) else: flash("文件为空或格式不对,上传失败!") return render_template('upload_action.html') flash("上传失败!") return render_template('upload_action.html')
def put(self): result = {"status": False} try: uid = self.get_argument("uid") username = self.get_argument("username") realname = self.get_argument("realname") password = self.get_argument("password", "") if not self.number.search(uid): lastrowid = User().update(username, password, realname, uid) result["message"] = "删除成功" result["status"] = True else: result["message"] = "UID错误" except Exception as e: print e result["message"] = "删除用户异常" self.write(json.dumps(result)) self.finish()
def post(self): result = {"status": False, "message": "用户名错误"} verifycode = xhtml_escape(self.get_argument("verifycode")).upper() if verifycode == self.get_secure_cookie("verifycode"): username = xhtml_escape(self.get_argument("username")) password = xhtml_escape(self.get_argument("password")) # sign_in : -1 - 用户名错误(default) # 0 - 密码错误 # 1 - 正确 sign_in = User().sign_in(username, password) if sign_in == 1: result["status"] = True self.set_secure_cookie("admin", username, expires_days=None) elif sign_in == 0: result["message"] = "密码错误" else: result["message"] = "验证码错误" self.write(json.dumps(result)) self.finish()
def login(): username = request.form.get('username', '') #接收用户提交的数据 password = request.form.get('password', '') #print request.form['username'] #print "username is %s" %username # _users,_error = user.get_info(username=username) # if _users: # _id = _users[0]['id'] # age = _users[0]['age'] # else: # _id = '' #希望把ID加进去作为session绑定,后面根据id修改对应用户的密码! #需要验证用户名密码是否正确 _user = User.validate_login(username, password) if _user: #判断用户登录是否合法 session['user'] = _user #设置session,绑定用户身份信息,和用户名绑定,类似办银行卡 flash("登陆成功!") #flask的消息闪现,一次生成一个, 通过函数get_flashed_messages()获取 print session #打印session信息,用于查看,理解session return redirect('/dashboard/') #跳转到url展示用户页面 else: #登录失败 return render_template('login.html', username=username, error='用户名或密码错误')
def __init__(self, auth_manager): # авторизация и получаем id try: self.spotify = spotipy.Spotify(auth_manager=auth_manager) self.user_id = self.spotify.current_user()['id'] # если юзера не сущестует в БД, то создаётся запись. Тут же создаётся запись для плейлиста if not User.query.filter_by(spotify_id=self.user_id).first(): db.session.add(User(spotify_id=self.user_id)) db.session.add(HistoryPlaylist(user_id=self.user_id)) db.session.add(FavoritePlaylist(user_id=self.user_id)) db.session.add(SmartPlaylist(user_id=self.user_id, max_tracks=100)) db.session.commit() self.user_query = User.query.filter_by(spotify_id=self.user_id).first() self.history_query = HistoryPlaylist.query.filter_by(user_id=self.user_id).first() self.favorite_query = FavoritePlaylist.query.filter_by(user_id=self.user_id).first() self.smart_query = SmartPlaylist.query.filter_by(user_id=self.user_id).first() self.settings = None except spotipy.exceptions.SpotifyException as e: app.logger.error(e)
def save(): user = User(1, 'jike') user.save()
def query_all(): users = User.query() for user in users: print user