def getUserByUsername(self, username): res = self.conn.execute("SELECT * FROM users WHERE username = '******'" % username).fetchone() if res == None: return None; usr = User(res['id'], res['username'], res.get('spojHandle')) usr.password = res['password']; return usr
def edit(self): # 参数 req = self.request() data = Inc.json_decode(req.get('data')) if not data or type(data)!=dict or not data.get('tel') : return self.getJSON({'code':4000,'msg':'参数错误!'}) uid = req.get('uid').strip() tel = data['tel'].strip() passwd = Inc.md5(data['passwd']) if data['passwd']!='' else '' # 验证手机 res = Safety.isRight('tel',tel) if not Safety.isRight('tel',tel) : return self.getJSON({'code':4000,'msg':'手机号码有误!'}) # 是否存在 res = User().findFirst({'where':'tel=:tel:','bind':{'tel':tel}}) if res : if passwd != '' : params = {'data': {'password':passwd}, 'where':'id=:uid:', 'bind':{'uid':uid}} if User().update(params) : return self.getJSON({'code':0,'msg':'成功'}) else : return self.getJSON({'code':5000,'msg':'更新密码失败!'}) else : return self.getJSON({'code':4000,'msg':'密码为6-16位字符!'}) # 修改手机 uData = {'tel':tel} if passwd != '' : uData['password']=passwd params = {'data': uData, 'where':'id=:uid:', 'bind':{'uid':uid}} if User().update(params) : return self.getJSON({'code':0,'msg':'成功'}) else : return self.getJSON({'code':5000,'msg':'编辑失败!'})
def add(self): # 参数 req = self.request() data = Inc.json_decode(req.get('data')) if not data or type(data)!=dict or not data.get('tel') : return self.getJSON({'code':4000,'msg':'参数错误!'}) tel = data['tel'].strip() passwd = Inc.md5(data['passwd']) if data['passwd']!='' else Inc.md5('123456') # 验证手机 res = Safety.isRight('tel',tel) if not Safety.isRight('tel',tel) : return self.getJSON({'code':4000,'msg':'手机号码有误!'}) # 是否存在 res = User().findFirst({'where':'tel=:tel:','bind':{'tel':tel}}) if res : return self.getJSON({'code':4000,'msg':'该用户已存在!'}) # 保存 params = { 'id': Data.getId(), 'tel': tel, 'password': passwd, 'rtime': Inc.date('%Y%m%d%H%M%S'), } # 结果 if User().insert(params) == 0 : return self.getJSON({'code':0,'msg':'成功'}) else : return self.getJSON({'code':5000,'msg':'添加失败!'})
def load_users(): delete_users() user_without_preferences = \ User(1, preferred_languages=[], favourite_actors=[], favourite_directors=[]) user_with_lang_pref = \ User(2, preferred_languages=["lan 1", "lan 3"], favourite_actors=[], favourite_directors=[]) user_with_actor_pref = \ User(3, preferred_languages=[], favourite_actors=["Actor 1"], favourite_directors=[]) user_with_director_pref = \ User(4, preferred_languages=[], favourite_actors=[], favourite_directors=["Director 1"]) users = [ user_without_preferences, user_with_actor_pref, user_with_director_pref, user_with_lang_pref ] user_ids = User.objects.bulk_create(users) print("Created users : ", user_ids)
def login(self): req = self.request() uname = req.get('uname') passwd = Inc.md5(req.get('passwd')) # 验证用户名 if Safety.isRight('uname', uname) and Safety.isRight( 'tel', uname) and Safety.isRight('email', uname): return self.getJSON({'code': 4000, 'msg': '请输入用户名/手机/邮箱'}) # 查询数据 uData = User().findFirst({ 'table': 'user as a LEFT JOIN user_info as b ON a.id=b.uid LEFT JOIN user_perm as c ON a.id=c.uid', 'columns': 'a.id, a.state, b.position, b.nickname, b.name, b.gender, b.img, c.state_admin', 'where': f'(a.uname="{uname}" OR a.tel="{uname}" OR a.email="{uname}") AND a.password="******"', }) # 是否存在 if uData == None: return self.getJSON({'code': 4000, 'msg': '帐号或密码错误'}) # 是否禁用 if uData['state'] != '1': return self.getJSON({'code': 4000, 'msg': '该用户已被禁用'}) elif uData['state_admin'] != '1': return self.getJSON({'code': 4000, 'msg': '该用户不允许登录'}) # 登录时间 User().update({ 'data': { 'ltime': Inc.date('%Y%m%d%H%M%S') }, 'where': 'id=' + str(uData['id']), }), # 返回 return self.getJSON({ 'code': 0, 'msg': '成功登录', 'uinfo': { 'uid': uData['id'], 'uname': uname, 'position': uData['position'], 'nickname': uData['nickname'], 'name': uData['name'], 'gender': uData['gender'], 'img': Env.base_url + uData['img'] if uData['img'] != '' else '', }, 'token': AdminToken().create({ 'uid': str(uData['id']), 'uname': uname }) })
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegisterForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', form=form)
def profile(): if not logged_in(): return redirect(url_for('login')) error = None if 'error' in request.args: error = request.args['error'] if request.method == 'POST': fname = request.form['fname'] lname = request.form['lname'] email = request.form['email'] username = session['username'] for name in (fname, lname): if not Person.check_name(name): return render_template("profile.html", error="Invalid name", fname=fname, lname=lname, email=email) if not Person.check_email(email): return render_template("profile.html", error="Invalid email", fname=fname, lname=lname, email=email) update_query = User.query_update_person(fname, lname, email, username) if update_query.code == DBQuery.CODE_OK: return redirect(url_for('profile')) return render_template("profile.html", error=ERROR_MSG, fname=fname, lname=lname, email=email) fname = "" lname = "" email = "" profile_data = User.get_person(session['username']) if profile_data.code == profile_data.CODE_OK: if profile_data.result: fname = profile_data.result[0][0] lname = profile_data.result[0][1] email = profile_data.result[0][2] return render_template("profile.html", fname=fname, lname=lname, email=email, error=error)
def add_user(): name = request.form['name'] mail = request.form['email'] nick = request.form['nick'] address_id = request.form['address'] address = session.query(Address).filter_by(id=address_id).scalar() u = User() u.name = name u.email = mail u.nick = nick u.address = address session.commit() return redirect(url_for('users'))
def init_db(): print(DATABASE_URI) print(Base.metadata.create_all(_engine)) dbsession = _create_session() phash = generate_password_hash('admin') admin = User(username='******', role='admin', password=phash) dbsession.add(admin) dbsession.commit()
def users_create(): form = request.form try: username = form['username'] if username == None or username == '': return jsonify({'status': 1, 'message': '用户名为空'}) password = form['password'] if password == None or password == '': return jsonify({'status': 2, 'message': '密码为空'}) password_again = form['password_again'] if password_again == None or password_again == '': return jsonify({'status': 3, 'message': '确认密码为空'}) if password_again != password: return jsonify({'status': 3, 'message': '两次密码不同'}) email = form['email'] if email == None or email == '': return jsonify({'status': 4, 'message': '邮箱空'}) if correct_email(email) == False: return jsonify({'status': 4, 'message': '邮箱格式错误'}) # sex = form['sex'] # nickname = form['nickname'] # 密码加密 password_encoded = password_encode(password) # db操作 db_session = DBSession() user = db_session.query(User).filter(User.username == username).first() if user is not None: db_session.close() return jsonify({'status': 1, 'message': '用户名已存在'}) email_db = db_session.query(User).filter(User.email == email).first() if email_db is not None: db_session.close() return jsonify({'status': 4, 'message': '邮箱重复'}) user = User(username=username, password=password_encoded, email=email) db_session.add(user) db_session.commit() user = db_session.query(User).filter_by(username=username).first() db_session.close() set_login(user) # 自动登录 return jsonify({'status': 0, 'message': '注册成功, 即将跳转个人中心完善个人信息'}) except Exception as e: print(e) return jsonify({'status': 5, 'message': '未知错误'})
def post(self): json_data = request.get_json(force=True) schema = { "type": "object", "properties": { "name": {"type": "string"}, "username" : {"type": "string"}, "email" : {"type": "string"}, "password" : {"type": "string"} } } validate(json_data, schema) name = json_data['name'] username = json_data['username'] email = json_data['email'] password = json_data['password'] # 동일한 아이디가 있으면 에러코드 1 : 실패 # 에러코드 0 : 성공 try: user = User.query.filter(User.username == username).one() except NoResultFound as e: join_date = datetime.now().strftime("%y/%m/%d") join_date = str(join_date) password_hashSHA = hashlib.sha256() password_hashSHA.update((password + join_date).encode('utf-8')) password = password_hashSHA.hexdigest() user = User(name=name, username=username, email=email, password=password, joinDate=join_date) db.session.add(user) db.session.commit() print("회원가입 성공: " + username) response = { "err": 0, "data": {} } return response print("회원가입 불가능 - 동일한 아이디 : " + username) response = { "err": 1, "data": {} } return response
def login(): error = None if 'error' in request.args: error = request.args['error'] if logged_in(): return redirect(url_for('index')) if request.method == 'POST': username = request.form['username'].lower() password = request.form['password'].lower() pwd_hash_role_query = User.query_hash_role(username) if pwd_hash_role_query.code == DBQuery.CODE_OK and pwd_hash_role_query.result: pwd_hash = pwd_hash_role_query.result[0][0] role = pwd_hash_role_query.result[0][1] if pwd_context.verify(password, pwd_hash): # If login successful log_in_as(username, role) return User.get_redirect_by_role(role) error = 'Invalid credentials' return render_template("login.html", error=error)
def CreateUser(): '''Untuk Membuat User Admin dan Mahasiswa''' try: # req_data = request.get_json() npm = request.form.get('npm') nama = request.form.get('nama') email = request.form.get('email') password = request.form.get('password') level = request.form.get('level') users = User(npm=npm, nama=nama, email=email, level=level) users.setPassword(password) db.session.add(users) db.session.commit() return response.success('', "Berhasil Menambahkan User") except Exception as e: print(e)
def signup(): data = request.get_json() username = data['username'] password = data['password'] email = data['email'] user = User(username, password, email) db.session.add(user) db.session.commit() return jsonify( {'response': 'User ' + username + ' created successfully'})
def register(): # if current_user.is_authenticated: # return redirect(url_for('.login')) form = RegistFrom() # if form.validate_on_submit(): == # username = User.query.filter_by(username=form.username.data.lower()).first() # if username is not None and User.vaildata_password(form.password.data) # if if request.method == 'POST' and form.validate_on_submit(): username = form.username.data password = form.password.data name = form.name.data user = User(username=username, password_hash=password, name=name) user.set_password(password) db.session.add(user) db.session.commit() flash(u'Thanks for registering', 'info') return redirect(url_for('.login')) logger.debug('db user id is %s, detail is %s' % (user.username, user)) return render_template('admin/register.html', form=form)
def post(self): try: json_data = request.get_json(force=True) username = json_data['username'] password = json_data['password'] now = datetime.now() due_date = str(now + timedelta(hours=3)) due_date_hashSHA = hashlib.sha256() due_date_hashSHA.update(due_date.encode('utf-8')) hash_date = due_date_hashSHA.hexdigest() try: user = User.query.filter(User.username == username).one() join_date = str(user.joinDate.strftime("%y/%m/%d")) password_hashSHA = hashlib.sha256() password_hashSHA.update((password + join_date).encode('utf-8')) password = password_hashSHA.hexdigest() print(password + "hello") except NoResultFound: join_date = datetime.now().strftime("%y/%m/%d") join_date = str(join_date) password_hashSHA = hashlib.sha256() password_hashSHA.update((password + join_date).encode('utf-8')) password = password_hashSHA.hexdigest() print(password + "joined") user = User(username=username, password=password, joinDate=join_date) db.session.add(user) db.session.commit() if user.password != password: return None, 403 else: token = Token(token=hash_date, dueDate=due_date, userId=user.id) db.session.add(token) db.session.commit() return token except Exception: return None, 400
def detail(): for param in ('arrival', 'departure', 'hid', 'rtid'): if param not in request.args: return render_template("no_results.html") arrival = datetime.datetime.strptime(request.args['arrival'], "%Y-%m-%d").date() departure = datetime.datetime.strptime(request.args['departure'], "%Y-%m-%d").date() hid = request.args['hid'] rtid = request.args['rtid'] if not logged_in(): session['search'] = [arrival.strftime("%Y-%m-%d"), departure.strftime("%Y-%m-%d"), hid, rtid] return redirect(url_for("login", error="Please log in or sign up to continue")) if 'search' in session: del session['search'] room_query = Booked.get_free_hotel_room(hid, rtid, arrival, departure) if room_query.code == DBQuery.CODE_OK and room_query.result: rid = room_query.result[0][0] else: return redirect(url_for('index', error='This order is no longer available')) if request.method == 'POST': checkin = datetime.datetime.strptime(request.form['checkin'], "%H:%M").time() checkout = datetime.datetime.strptime(request.form['checkout'], "%H:%M").time() person_query = User.get_person_id(session['username']) if person_query.code == DBQuery.CODE_OK: if not person_query.result: session['search'] = [arrival.strftime("%Y-%m-%d"), departure.strftime("%Y-%m-%d"), hid, rtid] return redirect(url_for("profile", error="Please fill your profile info")) pid = person_query.result[0][0] arrival = datetime.datetime.combine(arrival, checkin) departure = datetime.datetime.combine(departure, checkout) order_add_query = Booked.query_add(rid, pid, arrival, departure) if order_add_query.code == DBQuery.CODE_OK: return redirect(url_for('orders')) return redirect(url_for('index', error='This order is no longer available')) rtype_query = RoomType.get_roomtype(rtid) order_extra = Hotel.get_order_extra(hid) if rtype_query.code != DBQuery.CODE_OK or not rtype_query.result or order_extra.code != DBQuery.CODE_OK or not order_extra.result: return redirect(url_for('index', error='This order is no longer available')) info = order_extra.result[0] rtype = rtype_query.result[0][0] cost = ((departure - arrival).days + 1) * rtype_query.result[0][1] return render_template("detail.html", arrival=arrival, departure=departure, rtype=rtype, rid=rid, address=info[2:6], title=info[0], rating=info[1], cost=cost)
def create_user(): if request.method == 'GET': return render_template('user/create.html') nama = request.form['nama'] alamat = request.form['alamat'] jk = request.form['jk'] == 'laki_laki' umur = int(request.form['umur']) user = User(nama=nama, role='user', username=nama, alamat=alamat, jk=jk, umur=umur) dbsession = g.get('dbsession') dbsession.add(user) dbsession.commit() return redirect(url_for('admin.list_user'))
def list(self): req = self.request() # 搜索 data = Inc.json_decode(req.get('data')) uname = data['uname'] where = 'a.uname LIKE \"%:uname:%\" OR a.tel LIKE \"%:uname:%\" OR a.email LIKE \"%:uname:%\"' bind = {'uname':uname} # 查询 params = { 'table': 'user as a LEFT JOIN user_info as b ON a.id=b.uid', 'columns': 'a.id as uid,a.uname as uname,a.email as email,a.tel as tel,a.state as state,'+ 'a.rtime as rtime,a.ltime as ltime,a.utime as utime,'+ 'b.nickname as nickname,b.position as position,b.name as name,b.gender as gender,b.birthday as birthday,b.img as img', 'order': 'a.id DESC', 'where': where, 'bind': bind, } # 统计 total = User().count(params) # 分页 page = req.get('page') limit = req.get('limit') start = (int(page)-1)*int(limit) params['limit'] = str(start)+','+limit # 数据 list = User().find(params) # 状态 for val in list : val['state'] = True if val['state']=='1' else False val['uid'] = str(val['uid']) val['img'] = Env.base_url+str(val['img']) if val['img'] else '' val['birthday'] = str(val['birthday']) if val['birthday'] else '' val['rtime'] = str(val['rtime']) if val['rtime'] else '' val['ltime'] = str(val['ltime']) if val['ltime'] else '' val['utime'] = str(val['utime']) if val['utime'] else '' return self.getJSON({'code':0,'msg':'成功','list':list,'total':total})
def signup(): if logged_in(): return redirect(url_for('index')) if request.method == 'POST': username = request.form['username'].lower() password = request.form['password'].lower() if not User.check_username(username): return render_template("signup.html", error="Invalid username") if not User.check_password(password): return render_template("signup.html", error="Invalid password") # Check if user with given username already exists check_query = User.query_username(username) if check_query.code == DBQuery.CODE_OK: if check_query.result: return render_template("signup.html", error="Username %s is already taken" % username) else: return render_template("signup.html", error=ERROR_MSG) pwd_hash = pwd_context.encrypt(password) add_query = User.query_add(username, pwd_hash, User.ROLE_USER) if add_query.code == DBQuery.CODE_OK: # Automatically login user and redirect to profile page log_in_as(username, User.ROLE_USER) return redirect(url_for('profile')) else: return render_template("signup.html", error=ERROR_MSG) return render_template("signup.html")
def orders(): if not logged_in(): return redirect(url_for('login')) if request.method == 'POST': bid = request.form['bid'] username = session['username'] registered_check_query = User.registered_check_query(bid) if registered_check_query.code == DBQuery.CODE_OK: if not registered_check_query.result: delete_query = User.delete_person_order(username, bid) if delete_query.code == DBQuery.CODE_OK: return redirect(url_for('orders')) return render_template("orders.html", error=ERROR_MSG) orders_query = User.get_orders(session['username']) if orders_query.code == DBQuery.CODE_OK: orders_list = orders_query.result return render_template("orders.html", orders=orders_list) return render_template("orders.html", error=ERROR_MSG)
def post(self, ): data = request.get_json() user_name = sanitaze_user_input(data['user']) user_email = sanitaze_user_input(data['email']) try: u1 = User(username=user_name, email=user_email) db.session.add(u1) db.session.commit() except: db.session.rollback() u = User.query.filter(User.username == user_name).first() return {'user': u.username, 'email': u.email}, 200
def state(self): # 参数 req = self.request() uid = req.get('uid').strip() state = req.get('state').strip() if not uid or not state : return self.getJSON({'code':4000,'msg':'参数错误!'}) # 管理员 if uid=='1' : return self.getJSON({'code':4000,'msg':'禁止修改系统管理员!'}) # 更改 uData = {'state': '1' if state=='1' else '0'} params = {'data': uData, 'where':'id=:uid:', 'bind':{'uid':uid}} # 结果 if User().update(params) : return self.getJSON({'code':0,'msg':'成功'}) else : return self.getJSON({'code':5000,'msg':'更新失败!'})
def parse_users(file_path, user_file_name): with open(os.path.join(file_path, user_file_name)) as user_file: user_data = json.load(user_file) users = [] for x in user_data: users.append( list( map( lambda k, v: User( k, preferred_languages=v['preferred_languages'], favourite_actors=v['favourite_actors'], favourite_directors=v['favourite_directors']), x.keys(), x.values()))[0]) return users
def delete(self): # 参数 req = self.request() data = Inc.json_decode(req.get('data')) if not data : return self.getJSON({'code':4000,'msg':'参数错误!'}) # 管理员 if '1' in data or 1 in data : return self.getJSON({'code':4000,'msg':'无法删除系统管理员!'}) # ID ids = Inc.implode(',',data) user = {'where':'id in(:uid:)','bind':{'uid':ids}} uinfo = {'where':'uid in(:uid:)','bind':{'uid':ids}} # 结果 if User().delete(user) and UserInfo().delete(uinfo) : return self.getJSON({'code':0,'msg':'成功'}) else : return self.getJSON({'code':5000,'msg':'删除失败!'})
def create_new_user(): data_user_json = user_schema.load(request.json) # Checa se todos os dados foram informados e se não tem não existem dados nulos if len(data_user_json) < 3 or "" in data_user_json.values(): return jsonify({ 'success': False, 'message': 'Você deve informar todos os dados!' }), 401 email = data_user_json['email'] username = data_user_json['username'] password = data_user_json['password'] new_user = User(email=email, username=username, password=password, is_admin=False) current_app.db.session.add(new_user) current_app.db.session.commit() return jsonify({'success': True}), 201
def manager(): if not logged_in() or session['role'] != User.ROLE_MANAGER: abort(404) hotel_data = User.get_manager_hotel(session['username']) if hotel_data.code != DBQuery.CODE_OK or not hotel_data.result: abort(404) hotel_id = hotel_data.result[0][0] hotel_title = hotel_data.result[0][1] if request.method == 'POST': bid = request.form['bid'] if 'check_in' in request.form: reg_check = Registration.query_register_check_in(bid) else: reg_check = Registration.query_register_check_out(bid) if reg_check.code != DBQuery.CODE_OK: return render_template("manager.html", hotel=hotel_title, error=ERROR_MSG) return redirect(url_for('manager')) query_check_in = Booked.query_check_in(hotel_id) query_check_out = Booked.query_check_out(hotel_id) if query_check_in.code == DBQuery.CODE_OK: if query_check_out.code == DBQuery.CODE_OK: check_ins = [i for i in query_check_in.result] check_outs = query_check_out.result return render_template("manager.html", hotel=hotel_title, check_ins=check_ins, check_outs=check_outs) return render_template("manager.html", hotel=hotel_title, error=ERROR_MSG)
def addUser(): db.session.add( User(request.args.get('username'), request.args.get('email'))) db.session.commit() return 'add user success'
def post(self): json_data = request.get_json(force=True) schema = { "type": "object", "properties": { "name": { "type": "string" }, "username": { "type": "string" }, "email": { "type": "string" }, "phone": { "type": "string" }, "password": { "type": "string" }, "birthday": { "type": "string" } } } validate(json_data, schema) name = json_data['name'] username = json_data['username'] email = json_data['email'] phone = json_data['phone'] password = json_data['password'] birthday = json_data['birthday'] authority = "member" join_date = datetime.now().strftime("%y/%m/%d") join_date = str(join_date) password_hashSHA = hashlib.sha256() password_hashSHA.update((password + join_date).encode('utf-8')) password = password_hashSHA.hexdigest() try: user = User.query.filter(User.username == username).one() except NoResultFound as e: user = User(name=name, username=username, password=password, email=email, phone=phone,\ birthday=birthday, joinDate=datetime.now(), authority=authority) db.session.add(user) db.session.commit() print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), end="") print(" 사용자 등록 : " + name) response = {"err": 0, "data": {}} return response response = {"err": 1, "data": {}} return response
from app import db, app from app.model.Article import Article from app.model.User import User import time art1 = Article(title="tt", author='admin', content='dadadad', create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) user1 = User(account='5555', password='******', create_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), comment='ada') db.session.add(art1) db.session.add(user1) db.session.commit()
#!/usr/bin/python3 # -*- coding:utf-8 -*- from app.base.extensions import DBSession from app.model.User import User session = DBSession() new_user = User(username='******', password='******') session.add(new_user) session.commit() session.close()