def update_user(): """ 修改用户信息 :return: """ user_id = request.forms.user_id username = request.forms.username password = request.forms.password nickname = request.forms.nickname status = request.forms.status # 判断是否需要修改密码 if password == '': query = UserModel.update(username=username, nickname=nickname, status=status).where(UserModel.id == user_id) else: # 加密密码 password = hashlib.md5(password.encode("UTF-8")).hexdigest() query = UserModel.update( username=username, nickname=nickname, status=status, password=password).where(UserModel.id == user_id) if query.execute(): return {"code": 0} return {"code": -1}
def add_user(): """ 添加新用户 :return: """ username = request.forms.username password = request.forms.password nickname = request.forms.nickname status = request.forms.status create_time = datetime.datetime.now() # 加密密码 password = hashlib.md5(password.encode("UTF-8")).hexdigest() # 检测用户名是否存在 if UserModel.select().where(UserModel.username == username, UserModel.status != 2).count(): return {"code": -1} user = UserModel(username=username, password=password, nickname=nickname, status=status, create_time=create_time) user.save() return {"code": 0}
def post(self, gameKey: int) -> Response: payload: dict = request.json game: GameModel = GameModel.objects(game_key=gameKey).first() if not game: return Response('', 204) user: UserModel = UserModel.objects(user_id=payload['id'], game=game).first() if user: if check_password_hash(user.password, payload['password']): return jsonify({ 'accessToken': create_access_token(payload['id'], expires_delta=timedelta(days=10)) }) else: return Response('', 205) default_team: TeamModel = TeamModel.objects(game=game, team_id=0).first() UserModel(game, payload['id'], payload['email'], generate_password_hash(payload['password']), default_team).save() return jsonify({ 'accessToken': create_access_token(payload['id'], expires_delta=timedelta(days=10)) })
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {'message': 'This user is already exists'}, 400 user = UserModel(**data) user.save_to_db() return {"message": "User created successfully"}, 201
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "A user with that name already exists."}, 400 user = UserModel(**data) user.save_to_db() return {"message": "User created successfully."}, 201
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {'message': 'that username already exist'}, 400 user = UserModel(**data) #(data['username'], data['password']) user.add_to_db() return {'message': 'user registered successfully'}, 201
def register(): user_name = request.values['userName'] password = request.values['password'] if UserModel.find_by_username(user_name): return {"message": USER_ALREADY_EXIT}, 400 user = UserModel(user_name, password) user.save_to_db() return {"message": USER_OP.format("created")}, 201
def post(self): project = UserRegister.parser.parse_args() if UserModel.find_by_username(project['username']): return {'message':'A user with this username is already exist'}, 400 user = UserModel(**project) user.save_to_db() return {"Message": "User created successfully"}, 201
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data["username"]): return {"message": "A user with that username already exsits"}, 400 user = UserModel(data["username"], data["password"]) user.save_to_db() return {"message": "User created successfully"}, 201
def post(self): reqdata=UserRegister.parser.parse_args() existinguser=UserModel.find_by_username(reqdata['username']) print("reqdata is: ",reqdata) if existinguser: return ({'message':'user already exists'},400) newuser=UserModel(reqdata['username'],reqdata['password']) newuser.save_to_db() return ({'message':'user registered successfully'},201)
def post(self): data = arguments.parse_args() if UserModel.findByLogin(data['login']): return BadRequest('The informed login already exists.') if UserModel.findByEmail(data['email']): return BadRequest('The informed email already exists.') user = UserModel(**data) user.activated = False user.save() user.send_confirmation_email() return user.json(), 201
def post(self): data_load = request.get_json() try: data = UserSchema().load(data_load) except ValidationError as err: return err.messages, 404 if UserModel.find_by_username(data["username"]) is None: user = UserModel(data["username"], data["password"]) user.add_user() return {"response": "The user was successfuly created"}, 201 else: return dict(error="User with this username already exist"), 500
def post(self): data = User.parser.parse_args() user = UserModel.find(data["username"]) if user: return { "message": "User {} already exists".format(data["username"]) }, 400 user = UserModel(**data) user.save() return {"message": "User added"}, 201
def post(self): payload = request.json for key in ['id', 'password']: if key not in payload: abort(400) if UserModel.objects(id=payload['id']).first(): return Response('', 204) UserModel(id=payload['id'], pw=payload['password']).save() return Response('', 201)
def __init__(self, number): self.number = number self.db = db_test self.user = UserModel(self.db) self.group = GroupModel(self.db) self.article = ArticleModel(self.db) self.admin = { 'email': '*****@*****.**', 'penname': 'wutong', 'password': '******', } self.gen_test_data()
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "User already exists."} i = UserModel(**data) try: i.save_to_db() except: return { "message": "An error occurred." }, 500 # code for internal error return {"message": "User created successfully."}, 201
def get_user_by_username(username: str) -> UserModel: user = None # 邮箱登录 if '@' in username: if not validate_email(username): raise InvalidParam user = UserModel.objects(email=username).first() # 手机号登录 else: if not validate_phone(username): raise InvalidParam user = UserModel.objects(phone=username).first() return user
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data["username"]): return { "message": "A user with this username already exists in the database!" }, 400 user = UserModel(**data) user.save_to_db() return { "message": f"user {data['username']} has been created successfully!!" }
def post(self): data = Usersignup.parser.parse_args() if UserModel.get_user_by_name(data['username']): return { "message": "User already exists please enter new username" }, 400 # conn = sqlite3.connect('user.db') # cursor = conn.cursor() # cursor.execute("Insert into user values(NULL, ?,?)",(data['username'],data['password'])) # conn.commit() # conn.close user = UserModel(**data) user.save_to_db() return {"message": "User is created successfully"}, 201
def get(self, ): result_data = { 'error_code': 0, 'reason': 'ok', 'data': [], } uuid = self.get_argument('uuid', None) user_data = UserModel.get_by_uuid(uuid) if user_data: user_data.locked = True # print(self.dbs.dirty) self.dbs.add(user_data) try: self.dbs.commit() # print(user_data.locked) except Exception as e: print(e) self.dbs.rollback() result_data['error_code'] = 400 result_data['reason'] = '删除失败' finally: self.dbs.close() self.write_json(result_data)
def on_get(self, req, resp, id): #"""GET ALL USERS WHO HAVE A INTEREST"" db = MySQLdb.connect(host="localhost", user="******", passwd="123456", db="processodesoftware", charset="utf8", use_unicode=True) cursor = db.cursor() resp.status = falcon.HTTP_200 # Ok! id = int(id) #Executa a query sql = "SELECT id_user FROM user_interests WHERE id_skill = %s" % (id) cursor.execute(sql) #Recebe todos os resultados query = cursor.fetchall() #Cria uma lista guardar os dados convertidos queryObjects = [] #Converte for q in query: id = int(q[0]) #Executa a query sql = "SELECT id, nome, email, idade FROM users WHERE id = %d" % ( id) cursor.execute(sql) #Recebe todos os resultados query = cursor.fetchall() #Converte user = UserModel(query[0][0], query[0][1], query[0][2], query[0][3]) queryObjects.append(user.__dict__) resp.body = json.dumps(queryObjects) db.close()
def wrapper(*args, **kwargs): self = args[0] #该url处理器本身 if self.current_user: if UserModel.get_by_uuid(self.current_user.uuid).id == 1: return handler_method_func(*args, **kwargs) # self.write('not admin user!!!') self.redirect('/')
def post(self): result_dict, err_code = handle_request_validation_and_serialisation( order_creation_schema) if err_code: return result_dict, err_code if not result_dict['elements']: return { "message": "Cannot create an empty order. The order must have at least one element." }, 400 elements = result_dict['elements'] result_dict['elements'] = [] order = OrderModel(**result_dict) if not UserModel.find_by_id(order.user_id): return { "message": f"User with id: {order.user_id} does nor exist. " f"Cannot create an order for nonexistent user." }, 400 elements = [ OrderElementModel(**order_element_creation_schema.load(e)) for e in elements ] if err_msg := _validate_order_elements(elements): return err_msg, 400
def wrapper(*args, **kwargs): self = args[0] score = self.get_argument('score', None) # 总分 rightnum = self.get_argument('rightNum', None) # 答对数目 wrongnum = self.get_argument('wrongNum', None) # 答错数目 loudanum = self.get_argument('loudaNum', None) # 漏答数目 #判断用户是否登录 # print(self.current_user.uuid) if self.current_user: user_id = UserModel.get_by_uuid(self.current_user.uuid).id save_source = SourceModel(score=score, rightnum=rightnum, wrongnum=wrongnum, loudanum=loudanum, user_id=user_id) self.dbs.add(save_source) try: self.dbs.commit() except Exception as e: self.dbs.rollback() return handler(*args, **kwargs)
def post(self): '''注册逻辑判断''' username = self.get_argument("username", None) password1 = self.get_argument("password1", None) password2 = self.get_argument("password2", None) nickname = self.get_argument('nickname', None) result_data = { "error_code": 0, "reason": "ok", "result": [], } if CheckArgs.check_argument_reg(username, password1, password2): check_db = CheckArgs.check_user_in_db(username=username) #检出是否存在用户 if check_db: result_data["error_code"] = 414 result_data["reason"] = self.error_message[414] #self.write(json_data) else: user = UserModel.new(username, password=password1, nickname=nickname) # print('reg:', user) if user.uuid: self.clear_all_cookies() self.set_secure_cookie('uuid', user.uuid, expires_days=7) # print(user.uuid) else: result_data["error_code"] = 415 result_data["reason"] = self.error_message[415] else: result_data["error_code"] = 410 result_data["reason"] = self.error_message[410] self.set_header('Content-Type', 'application/json;charset=utf-8') self.write_json(result_data)
def _post_addadmin(self): userid = self.get_body_argument('userid', default='') password = self.get_body_argument('password', default='') repassword = self.get_body_argument('repassword', default='') # 两次输入的密码不匹配 if password != repassword: self._json('fail', '两次密码不匹配') # 密码长度太短 if len(password) < 6: self._json('fail', '密码设置过短') # 加密密码 password = yield self.backend.submit(hash.get, password) oldadmin = yield self.db.admin.find_one({'userid': userid}) # 用户id已存在 if oldadmin: self._json('fail', '用户id已存在, 请更换') # 添加用户 user = { 'userid': userid, 'password': password, 'power': 20, 'registertime': time.time(), 'faceurl': '/static/assets/img/user04.png' } model = UserModel() if not model(user): self._json('fail', model.error_msg) result = yield self.db.admin.insert(user) self._json('success')
def delete(self): uid = int(self.get_argument('id')) users = UserModel.mgr(ismaster=1).Q().filter(id=uid) if users: for user in users: user.delete() self.send_json({}, 0, '成功')
def _post_edit(self): profile = {} profile["email"] = self.get_body_argument("email", default=None) profile["website"] = self.get_body_argument("website", default=None) profile["qq"] = self.get_body_argument("qq", default=None) profile["address"] = self.get_body_argument("address", default=None) profile["signal"] = self.get_body_argument("signal", default=None) orgpass = self.get_body_argument("orgpass", default=None) if orgpass: password = self.get_body_argument("password") repassword = self.get_body_argument("repassword") if not password or len(password) < 5: self.custom_error("新密码太短") if password != repassword: self.custom_error("两次输入的密码不相同") user = yield self.db.member.find_one( {"username": self.current_user["username"]}) check = yield self.backend.submit(hash.verify, orgpass, user["password"]) if not check: self.custom_error("原始密码输入错误") profile["password"] = yield self.backend.submit(hash.get, password) if profile["email"].endswith('@tjchtech.com'): self.custom_error("由于邮件域名问题,不能使用公司邮箱") # check user profile model = UserModel() if not model(profile): self.custom_error(model.error_msg) yield self.db.member.update( {"username": self.current_user["username"]}, {"$set": profile}) self.redirect("/user/edit")
def post(self): vl = req.get_json() isUserId = bool(vl[0].get('userId')) isStoreId = bool(vl[0].get('storeId')) if isStoreId: authorId = vl[0]['storeId'] isExistStoreId = StoreModel.findByStoreId(authorId) if not bool(isExistStoreId): return gettex('NOT_FOUND'), 404 else: authorId = vl[0]['userId'] isExistUserId = bool(UserModel.findById(authorId)) islimit = ProductModel.isLimit(authorId) if not isExistUserId: return gettex('NOT_FOUND'), 422 if islimit: return gettex('LIMITED'), 401 serial = ProductModel.findSerial() for value in vl: serial += 1 proId = ProductModel.newProid(authorId, serial) value.update({'proId': proId}) product = ProductSchema(many=True).load(vl, session=db.session) ProductModel.insertMany(product) return gettex('SUCCESS'), 201
def get(self, ): uuid = self.get_argument('uuid', None) data = UserModel.get_by_uuid(uuid) self.render( 'control/edit-data.html', data=data, )
def post(self): ''' 检查用户传入参数,并验证数据库信息 :return: ''' username = self.get_argument('username', None) password = self.get_argument('password', None) result_data = { "error_code": 0, "reason": "ok", "result": [], } if (not username) or (not password): result_data["error_code"] = 400 result_data["reason"] = self.error_message[400] else: if CheckArgs.check_argument_login(username, password): check_user_data = UserModel.check_user_in_db(username, password) if check_user_data: # print(UserModel.get_by_username(username), check_user_data) result_data["error_code"] = 0 self.clear_all_cookies() self.set_secure_cookie('uuid', check_user_data.uuid, expires_days=7) else: result_data["error_code"] = 400 result_data["reason"] = self.error_message[400] else: result_data["error_code"] = 400 result_data["reason"] = self.error_message[400] self.set_header('Content-Type', 'application/json;charset=utf-8') self.write_json(result_data)
def get_users(): """ 获取所有用户 :return: """ response.set_header("Content-Type", "application/json") users = UserModel.select().where(UserModel.status != 2).order_by(UserModel.id.desc()) r = list(map(UserModel.get_dict_from_obj, users)) return json.dumps(r)
def check(self): userName = self.get_argument('userName', '').encode('utf-8') passWord = self.get_argument('passWord', '') sql = "select * from monitor_user where userName='******' and passWord='******'" % (userName, passWord) users = UserModel.mgr().raw(sql) res = dict() if len(res) > 0: self.send_json(users[0], 0, '登陆成功') else: self.send_json({}, 1, '用户名或密码错误,登陆失败')
def list(self): size = int(self.get_argument('size', '10')) page = int(self.get_argument('page', '0')) if page == 0: page = 0 if size == 0: size = 10 sql = 'select * from monitor_user limit %d,%d' % (page * size, size); users = UserModel.mgr().raw(sql) self.send_json(users, 0 , '成功')
def delete_user(user_id): """ 删除一个用户 :param user_id: 用户id :return: """ dao = UserModel.update(status=2).where(UserModel.id == user_id) dao.execute() return redirect("/admin/user")
def userlist(self): # 列表的当前页,默认在第一页 currentPage = int(self.get_argument('pageNum', 1)) # 列表中每页显示多少条,默认每页显示20条 numPerPage = int(self.get_argument('numPerPage', 20)) searchWord = self.get_argument('searchWord', '') # 计算User的总数 if searchWord != '': sql = "select * from monitor_user where userName like '%%%%%s%%%%'" % searchWord all = UserModel.mgr().raw(sql) else: all = UserModel.mgr().Q() totalCount = len(all) users = all[(currentPage - 1) * numPerPage: currentPage * numPerPage] self.render('user/list.html', users=users, currentPage=currentPage, numPerPage=numPerPage, totalCount=totalCount, searchWord=searchWord);
def update_user(): """ 修改用户信息 :return: """ user_id = request.forms.user_id username = request.forms.username password = request.forms.password nickname = request.forms.nickname status = request.forms.status # 判断是否需要修改密码 if password == '': query = UserModel.update(username=username, nickname=nickname, status=status).where(UserModel.id == user_id) else: # 加密密码 password = hashlib.md5(password.encode("UTF-8")).hexdigest() query = UserModel.update(username=username, nickname=nickname, status=status, password=password).where(UserModel.id == user_id) if query.execute(): return {"code": 0} return {"code": -1}
def save(self): uid = self.get_argument('id', '') imei = self.get_argument('imei', '') userName = self.get_argument('userName', '').encode('utf-8') passWord = self.get_argument('passWord', '') phoneNumber = self.get_argument('phoneNumber', '') user = UserModel.new() if uid != '': user.id = uid user.imei = imei user.userName = userName user.passWord = passWord user.phoneNumber = phoneNumber resUser = user.save() self.send_json(resUser, 0, '成功')
def login(): """ 用户登录 :return: """ username = request.forms.username password = request.forms.password password = hashlib.md5(password.encode("UTF-8")).hexdigest() try: user = UserModel.select().where(UserModel.username == username, UserModel.password == password, UserModel.status == 0).get() request.session['uid'] = user.id except: return {"code": -1} return {"code": 0}
def usersave(self): id = self.get_argument('id', '') passWord = self.get_argument('passWord', '') userName = self.get_argument('userName', '') imei = self.get_argument('imei', '') phoneNumber = self.get_argument('phoneNumber', '') user = UserModel.new() if id != '': user.id = id user.userName = userName user.phoneNumber = phoneNumber user.imei = imei user.passWord = self.md5(passWord) user.save() self.write(json.dumps({'statusCode': "200", 'callbackType': "closeCurrent", 'navTabId': "user", 'forwardUrl': "/admin/userlist"}))
def bootstrap(provider_key): user_keys = [] user = UserModel() user.username = '******' user.role = ROLE_APP_CLIENT user.authToken = hashlib.md5('webapp').hexdigest() user.put() user = UserModel(parent=provider_key) user.username = '******' user.firstName = 'Michael' user.lastName = 'Landes' user.authToken = hashlib.md5('mlandes3').hexdigest() user.role = ROLE_BASIC_USER user_keys.append(user.put()) user = UserModel(parent=provider_key) user.username = '******' user.firstName = 'Pranav' user.lastName = 'Ram' user.authToken = hashlib.md5('pram8').hexdigest() user.role = ROLE_BASIC_USER user_keys.append(user.put()) user = UserModel(parent=provider_key) user.username = '******' user.firstName = 'Ian' user.lastName = 'Wilson' user.authToken = hashlib.md5('iwilson7').hexdigest() user.role = ROLE_BASIC_USER user_keys.append(user.put()) user = UserModel(parent=provider_key) user.username = '******' user.firstName = 'Yaohong' user.lastName = 'Xi' user.authToken = hashlib.md5('yxi8').hexdigest() user.role = ROLE_BASIC_USER user_keys.append(user.put()) return user_keys
def get_all_users(provider_key_id=None): ancestor_key = ndb.Key(urlsafe=provider_key_id) if provider_key_id else None users = UserModel.query(ancestor=ancestor_key).fetch() return users
def get_users_by_username(username, provider_key_id=None): ancestor_key = ndb.Key(urlsafe=provider_key_id) if provider_key_id else None users = UserModel.query(ancestor=ancestor_key).filter(UserModel.username == username) return users