def seed(): wipe() if not UserModel.exists(): UserModel.create_table(read_capacity_units=1, write_capacity_units=1, wait=True) if not Connection.exists(): Connection.create_table(read_capacity_units=1, write_capacity_units=1, wait=True) return "Done!"
def delete(self, user_id): try: UserModel.delete_by_id(self.db, user_id) self.finish_json() except Exception, e: print e self.finish_json(errcode=200, errmsg=str(e))
def insert_user(self, request): current_user = endpoints.get_current_user() if current_user is None: raise endpoints.UnauthorizedException('Authorization required') logging.info('user '+str(current_user)) user_id = (current_user.user_id() if current_user is not None and current_user.user_id() is not None else 'Anonymous') email = (current_user.email() if current_user is not None else '*****@*****.**') query = UserModel.query(UserModel.email == email).fetch() logging.info('LEN '+str(len(query))) userDb = None if len(query) > 0: userDb = query[0] logging.info('DB '+str(userDb)) else: userDb = UserModel(user_id=user_id , email=email) userDb.key = ndb.Key('UserModel',email) userDb.put() key = userDb.key.urlsafe() #key = userDb.key.id() user = User(user_id=userDb.user_id, email=userDb.email, key=str(key)) return user
def put(self): args = self.get_json_arguments() old_password, password, re_password = get_and_valid_arguments(args, 'old_password', 'password', 're_password') old_password = md5_password(old_password) if self.current_user.password != old_password: print u'密码不对' print self.current_user.password, old_password self.finish_json(1, u'旧密码不正确') return if (not password) or (not re_password): print u'请输入正确密码' self.finish_json(1, u'请输入正确密码') return if password != re_password: print u'两次密码不一致' self.finish_json(1, u'两次密码不一致') return if md5_password(password) == self.current_user.password: print u'新密码和旧密码相同' self.finish_json(1, u'新密码和旧密码相同') return UserModel.update_password(self.db, self.current_user.merchant_id, self.current_user.username, password) self.clear_cookie('username') self.clear_cookie('merchant_id') self.finish_json(0, '修改成功')
def get(self,uid): user_model = UserModel() book_model = BookModel() info = user_model.get_user(uid) current = book_model.get_current(uid) data = {} current_list = [] for book in current: item = {} item["rent_time"] = book[0].date() item["return_time"] = book[1].date() item["title"] = book[2] item["images"] = book[3] item["author"] = book[4] item["isbn"] = book[5] item["address"] = book[6] current_list.append(item) data["current"] = current_list uinfo = {} for user in info: uinfo["name"] = user[0] uinfo["gravator"] = user[1] uinfo["major"] = user[2] uinfo["degree"] = user[3] uinfo["num"] = user[4] uinfo["id"] = user[5] data["uinfo"] = uinfo self.render("user.html",data=data)
def post(self): number = self.get_argument("number") passwd = self.get_argument("passwd") select = self.get_argument("select") user = {"number": number} # user info object post = { "number": number, "passwd": passwd, "select": select } user_model = UserModel() user = user_model.get_info(post["number"]) # 判断用户是否已经存在 if not user: user = User(post).import_user() # import users book_model = BookModel() if user_model.import_user(user,post["number"]): user = user_model.get_info(user["number"]) # 判断用户是否已经导入数据 if book_model.is_import(user["id"]): book = Book(post).get_remote_book(True) else: book = Book(post).get_remote_book(False) book_model.import_book(book,user["id"]) # 将用户信息存入cookie self.set_current_user(user) self.write(json.dumps({"error_code":"200"}))
def put(self, user_id): data = json_decode(self.request.body) if not self.valid_new_user(data['username'], data['password'], data['nickname'], data['department'], data['permission']): self.finish_json(errcode=400, errmsg='wrong argument') return else: user = UserModel.get_user_by_id(self.db, user_id) if user is None: self.finish_json(errcode=404, errmsg="user id not exist") return else: tmp_user = UserModel.get_user_by_username( self.db, data['username']) if tmp_user and (tmp_user.id != int(user_id)): print 'exist username' self.finish_json(errcode=409, errmsg="username exist") return try: UserModel.update_by_id(self.db, user_id, data['username'], data[ 'password'], data['nickname'], data['department'], data['permission']) self.finish_json() return except Exception, e: print e self.finish_json(errcode=507, errmsg=str(e)) return
def calc_new_trust(self): winner = AnswerModel.get_by_answer_id(self.best_answer_id) loser = AnswerModel.get_by_answer_id(self.other_answer_id) new_trust = UserModel.newTrust(winner.userID, loser.userID) UserModel.setTrust(winner.userID,new_trust[0]) UserModel.setTrust(loser.userID,new_trust[1])
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "User with that username already exists."}, 400 user = UserModel(**data) user.save_to_db() return {"message": "User created successfully."}, 201
def post(self): data = _user_parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "A user with that username already exists"}, 400 user = UserModel(data['username'], data['password']) user.save_to_db() return {"message": "User created successfully."}, 201
def render(self): if self.debug: return render_template('index_debug.html', lti_dump=g.lti.dump_all()) if g.lti.is_instructor(): return render_template('question_list.html') else: UserModel.save(g.lti.get_user_id(), g.lti.get_user_name()) return render_template('index_student.html')
def post(self): args = self.get_json_arguments() merchant_id, username, password, re_password, department, mobile, authority, is_valid = \ get_and_valid_arguments( args, 'merchant_id', 'username', 'password', 're_password', 'department', 'mobile', 'authority', 'is_valid') hotel_id = None if 'hotel_id' in args: hotel_id = args['hotel_id'] try: hotel_id = int(hotel_id) authority = 0 authority += PERMISSIONS.update_order authority += PERMISSIONS.view_cooperated_hotel authority += PERMISSIONS.view_order authority += PERMISSIONS.inventory authority += PERMISSIONS.pricing authority += PERMISSIONS.update_password except Exception: self.finish_json('1', u'不合法的酒店') return if merchant_id != self.current_user.merchant_id: self.finish_json(1, u'您只能管理自己的酒店') return if not username: self.finish_json(1, u'请填写用户名') return if (not password) or (not re_password): self.finish_json(1, u'请输入密码') return if password != re_password: self.finish_json(1, u'两次密码不一致') return if not department: self.finish_json(1, u'请输入部门') return if not mobile: self.finish_json(1, u'请输入手机号') return if authority & PERMISSIONS.admin or authority & PERMISSIONS.root: self.finish_json(1, u'不允许添加管理员用户') return user = UserModel.get_user_by_merchantid_username( self.db, merchant_id, username) if user: self.finish_json(1, u'用户名已被使用') else: UserModel.add_user(self.db, merchant_id, username, password, department, mobile, authority, is_valid, hotel_id) self.finish_json(0, u'添加成功')
def modify_merchant(self, id, name, type, admin_pwd, root_pwd): merchant = MerchantModel.get_by_id(self.db, id) if not merchant: raise JsonException(errcode=404, errmsg="merchant not fount") else: merchant.update(self.db, name, type) if admin_pwd: UserModel.update_password(self.db, merchant.id, 'admin', admin_pwd) if root_pwd: UserModel.update_password(self.db, merchant.id, 'root', root_pwd) return merchant
def put(self): args = self.get_json_arguments() merchant_id, username, department, mobile, authority, is_valid = \ get_and_valid_arguments( args, 'merchant_id', 'username', 'department', 'mobile', 'authority', 'is_valid') hotel_id = None if 'hotel_id' in args: hotel_id = args['hotel_id'] try: authority = None hotel_id = int(hotel_id) except Exception: self.finish_json('1', u'不合法的酒店') return if 'email' in args: email = args['email'] else: email = None if 'password' in args: password = args['password'] else: password = None if not self.mobile_check(mobile): self.finish_json(1, u'请填写正确手机号') return if not department: self.finish_json(1, u'请填写部门') return if self.current_user.merchant_id != merchant_id: self.finish_json(1, u'您只能管理自己的酒店') return ''' 可以管理用户 ''' UserModel.update_user(self.db, merchant_id, username, password, department, mobile, email, is_valid, authority, hotel_id) ''' 修改了自己的密码 ''' if self.current_user.username == username and password: self.clear_cookie('username') self.clear_cookie('merchant_id') self.finish_json(301, self.get_login_url()) return self.finish_json(0, u'成功')
def add_user(user): logging.info("user " + str(user)) user_id = user.user_id() if user is not None and user.user_id() is not None else "Anonymous" email = user.email() if user is not None else "*****@*****.**" query = UserModel.query(UserModel.email == email).fetch() logging.info("LEN " + str(len(query))) userDb = None if len(query) > 0: userDb = query[0] logging.info("DB " + str(userDb)) else: userDb = UserModel(user_id=user_id, email=email) userDb.key = ndb.Key("UserModel", email) userDb.put() return userDb
def validateUserId(userId): isValid = UserModel.doesUserExistById(userId) if(not isValid): userId = {"message":'\'userId\' doesn\'t exist in our database.'} return (isValid, userId)
def validateFacebookId(facebookId): isValid = UserModel.doesUserExistByFacebookId(facebookId) if(not isValid): facebookId = {"message":'\'facebookId\' doesn\'t exist in our database.'} return (isValid, facebookId)
def __init__(self, question_id): schedule_list = [] user_list = [] scores = [] answers = AnswerModel.get_question_answers(question_id) for a in answers: uid = a.userID scores.append((UserModel.getTrust(uid), a)) user_list.append(a.userID) scores.sort(key=lambda tup: tup[0]) # TODO: possibly change fixed percentage to variable # IMPORTANT: users that did not give an answer should be able to rate, # not sure if that will happen right now # # initial scheduler shift_count = len(scores) - max(1, int(len(scores) * 0.2)) user_list = user_list[shift_count:] + user_list[0:shift_count] for x in xrange(0, len(scores)): a_id = scores[x][1].id u_id = user_list[x] schedule_list.append((a_id, u_id)) Schedule.add_list(schedule_list)
def send_order_sms(self, merchant_id, hotel_name, order_id, confirm_type): Log.info(u">>> send sms to merchant {} hotel {} order_id {} confirm type {}".format(merchant_id, hotel_name, order_id, confirm_type)) order = OrderModel.get_by_id(self.session, order_id) breakfast_str = u'含早' if order.get_has_breakfast() else u'无早' customers = json.loads(order.customer_info) customer_str = " ".join([customer['name'] for customer in customers]) if confirm_type == OrderModel.CONFIRM_TYPE_AUTO: content = u"尊敬的用户您好,系统收到编号{}自动确认订单:{},房型:{},入离日期:{}至{}( {}晚 ),入住人:{},总价:{},{}。订单号:{},请及时关注。客服联系电话:4006103330".format(merchant_id, hotel_name, order.roomtype_name, order.checkin_date, order.checkout_date, order.get_stay_days(), customer_str, order.total_price / 100, breakfast_str, order_id) elif confirm_type == OrderModel.CONFIRM_TYPE_MANUAL: content = u"尊敬的用户您好,系统收到编号{}待确认订单:{},房型:{},入离日期:{}至{}( {}晚 ),入住人:{},总价:{},{}。订单号:{},请尽快处理。客服联系电话:4006103330".format(merchant_id, hotel_name, order.roomtype_name, order.checkin_date, order.checkout_date, order.get_stay_days(), customer_str, order.total_price / 100, breakfast_str, order_id) send_sms_to_service(merchant_id, content) user =UserModel.get_user_by_merchantid_username(self.session, merchant_id, 'admin') if not user: Log.info("send sms no user(order {})".format(order_id)) return phone = user.mobile if not phone: Log.info("send sms no phone(order {})".format(order_id)) return Log.info(">> send sms to {}".format(phone)) Log.info(u">> sms content: {}".format(content)) send_sms([phone], content)
def test_register_user(self): with self.app() as client: with self.app_context(): response = client.post('/register', data={'username':'******', 'password':'******'}) self.assertEqual(response.status_code, 201) self.assertIsNotNone(UserModel.find_by_username('test')) self.assertDictEqual({'message':'User created successfully.'}, json.loads(response.data))
def post(self): username = cgi.escape(self.request.get("inputUsername")) email = cgi.escape(self.request.get("inputEmail")) password = cgi.escape(self.request.get("inputPassword")) if(email is not None and password is not None): logging.info('Register '+username+" - "+email+" - "+password) user = UserModel(user_id=username, email=email, password=password) userKey = user.put() logging.info(userKey) logging.info(userKey.id()) logging.info(userKey.kind()) userDb = userKey.get() logging.info(userDb) else: template = JINJA_ENVIRONMENT.get_template('templates/pages/register.html') self.response.write(template.render())
def student_question(self, request): if g.lti.is_instructor(): rv = [] user_questions = UserQuestion.get_list(5) for q in user_questions: user = UserModel.by_user_id(q.user_id) if user is not None: rv.append({'user':user.username, 'text':q.text, 'id':q.id}) else: rv = dict({'error': True, 'type': ''}) try: text = request.form['text'] except KeyError: rv['type'] = 'key' return json.dumps(rv) min_delay = 10 dt = UserQuestion.time_since_last(g.lti.get_user_id()) if dt is not None and dt < min_delay: rv['type'] = 'time' else: rv['error'] = False UserQuestion.add(g.lti.get_user_id(), text) return json.dumps(rv)
def get(self): users = UserModel.get_users_by_merchant_id(self.db, self.current_user.merchant_id) mappings = UserHotelMappingModel.get_hotel_by_id(self.db, None, self.current_user.merchant_id) if mappings: map_ids = {map.user_id: map.hotel_id for map in mappings} for user in users: user.hotel_id = map_ids.get(user.id) self.finish_json( 0, u'成功', json_encode([user.todict() for user in users]))
def test_register_user(self): with self.app() as client: with self.app_context(): response = client.post('/register', data = {'username': '******', 'password': '******'}) self.assertEqual(response.status_code, 201) self.assertIsNotNone(UserModel.find_by_username('test')) # json.loads() used to convert json format to python dictionary self.assertDictEqual({"message": "User created successfully."}, json.loads(response.data))
def get_user(gplus_id): try: user = UserModel.get(gplus_id) response = make_response("user: "******"User Not Found: {0}".format(gplus_id)
def identity(payload): """ Function that gets called when user has already authenticated, and Flask-JWT verified their authorizations header is correct. :param payload: A dictionary with 'identity' , key, which is the user id. :return: A UserModel object. """ user_id = payload['identity'] return UserModel.find_by_id(user_id)
def list_users(self, request): usersList = UserModel.query().fetch() items = [] for userItem in usersList: items.append(User(user_id=userItem.user_id, email=userItem.email, key=str(userItem.key.id()), strava_id=userItem.strava_id, strava_token=userItem.strava_token)) return UserCollection(data = items)
def authenticate(username, password): """ Function that gets called when a user calls the /auth endpoint with their username and password :param username: User's username in string format. :param password: User's un-encrypted password in string format. :return: A user if authentication was successful, None otherwise. """ user = UserModel.find_by_username(username) if user and safe_str_cmp(user.password, password): return user
def get_friends(gplus_id): try: friends = UserModel.get(gplus_id).friends() app.logger.debug("found {0} friends".format(len(friends))) friends_json = [] for friend in friends: friends_json.append(friend.to_json()) response = make_response(json.dumps(friends_json, indent=2), 200) response.headers['Content-Type'] = 'application/json' return response except UserModel.DoesNotExist: app.logger.debug('User does not exist') return "User Not Found: {0}".format(gplus_id)
def test_crud(self): with self.app_context(): user = UserModel('test', 'abcd') self.assertIsNone(UserModel.find_by_username('test'), "Found an user with name 'test' before save_to_db") self.assertIsNone(UserModel.find_by_id(1), "Found an user with id '1' before save_to_db") user.save_to_db() self.assertIsNotNone(UserModel.find_by_username('test'), "Did not find an user with name 'test' after save_to_db") self.assertIsNotNone(UserModel.find_by_id(1), "Did not find an user with id '1' after save_to_db")
def authenticate(username, password): #Get user from database user = UserModel.find_by_username(username) #If user exists, and password matches return user if user and safe_str_cmp(user.password, password): return user
def identity(payload): # user = id_mapping.get(payload['identity'], None) user = UserModel.find_by_id(payload['identity']) return user
def identity(payload):#payload is content of jwt token user_id = payload['identity'] return UserModel.find_by_id(user_id)
def identity(payload):#payload is the content of JSON JWT tokens user_id = payload['identity'] return UserModel.find_by_id(user_id)
def identity(payload): id = UserModel.find_by_id(payload['identity']) # user_id=payload['identity'] return id
def add_claims_to_jwt(identity): user = UserModel.find_by_id(identity) return {"username": user.username, "email": user.email}
def identity(payload): user_id = payload['identity'] print("user_id:", user_id) return UserModel.find_by_id(user_id)
def get(cls, user_id: int): user = UserModel.find_by_id(user_id) if not user: return {"message": USER_NOT_FOUND}, 404 return user_schema.dump(user), 200
def get(cls, username): user = UserModel.find_by_username(username) if not user: return {'message': USER_NOT_FOUND}, 404 return {'user': user_schema.dump(user)}, 200
def get(self): print(current_identity) return [{ "username": user.username, "password": user.password } for user in UserModel.find_all()], 200
def authenticate(username, password): user = UserModel.find_user_by_username(username) if user and safe_str_cmp(user.password, password): return user
def post(self): data = self.parser.parse_args() user = UserModel.find_by_username(data['username']): return {"message": "A user with that username already exists"}, 400
def identity(payload): return UserModel.find_user_by_id(payload['identity'])
def _pre_dump(self, user: UserModel, **kwargs): """Use to modify the user before dumping. This will change the confirmation to be a list with only the last confirmation""" user.confirmation = [user.most_recent_confirmation] return user
def authenticate(username, password): user = UserModel.find_by_username(username) if user: user.password == password return user
def get(cls, user_id): user = UserModel.find_by_id(user_id) if not user: return {'message': 'User not found'}, 404 return user.json()
def get(self, user_id): user = UserModel.find_user(user_id) if user: return user.json() return {"message": "User not found."}, 404
def _pre_dump(self, user: UserModel) -> UserModel: user.confirmation = [user.most_recent_confirmation] return user
def get(cls, user_id: int): user = UserModel.find_by_id(user_id) if not user: return {"message": gettext("user_not_found")}, 404 return user_schema.dump(user), 200
def delete(cls, user_id): user = UserModel.find_by_id(user_id) if not user: return {"message": "User not found"}, 404 user.delete_from_db() return {"message": "User deleted"}, 200
def authenticate(username, password): user = UserModel.find_by_name(username) # user=user_mapping.get(username,None) if user and user.password == password: return user
def authenticate(username, password): # user = username_mapping.get(username, None) user = UserModel.find_by_username(username) if user and safe_str_cmp(user.password, password): return user
def delete(cls, user_id): user = UserModel.find_by_id(user_id) if not user: return {'message': 'User not found'}, 404 user.delete_from_db() return {'message': 'User deleted!'}, 200
def get(cls, user_id): user = UserModel.find_by_id(user_id) if not user: return {"message": "User not found"}, 404 return user.json()
def authenticate(username, password): user = UserModel.find_by_username(username) if user and safe_str_cmp( user.password, password ): # use safe_str_cmp to safely compare strings accross apps and versions return user
def identity(payload): user_id = payload['identity'] return UserModel.find_by_id(user_id)
def get(cls, row_id): user = UserModel.find_by_id(row_id) if not user: return {'message': 'User Does Not Exist'}, 404 return user.json(), 200
def add_sender_info(self, obj): return user_schema.dump(UserModel.find_by_id(obj.sent_by))
def authenticate(username, password): user = UserModel.find_by_username(username) if user and check_password_hash(user.password, password): return user
def delete(self, name): korisnik = UserModel.find_by_username(name) if korisnik: korisnik.delete_from_db() return {'msg': 'Korisnik uspesno izbrisan.'}