def test_user_update_holder(self): # 1. create users user1 = User(uid="test0", name="test0", secret="1111") user2 = User(uid="test1", name="test1", secret="1111") # 2. imitate dialog # dialog_holders = DialogsHolders.get_instance() # # list_of_users = list() # list_of_users.append(user1.uid) # list_of_users.append(user2.uid) # # success, dialog = dialog_holders.create_dialog(list_of_users=list_of_users) # 3. prepare messages msg1 = Message(dialog_id="test", text="test text", from_id=user1.uid, time_stamp=-1) msg2 = Message(dialog_id="test", text="text test", from_id=user2.uid, time_stamp=-2) # 4. prepare update holders update_holder_u1 = UserUpdateHolder(user_id=user1.uid) update_holder_u2 = UserUpdateHolder(user_id=user2.uid) update_holder_u1.add(message=msg1, dialog_id="test") update_holder_u1.add(message=msg2, dialog_id="test") update_holder_u1_dict = update_holder_u1.get_as_dict() update_holder_u2_dict = update_holder_u2.get_as_dict() j_result = update_holder_u1.get_as_json() print "[test_user_update_holder] test cases finished" pass # do not know how to automate validation -> seems to be OK
def test_user_history_holder(self): ##### # from previous test # 1. create users user1 = User(uid="uid_test0", name="name test0", secret="secr1111") user2 = User(uid="uid_test1", name="name test1", secret="secr1111") # 2. imitate dialog # dialog_holders = DialogsHolders.get_instance() # # list_of_users = list() # list_of_users.append(user1.uid) # list_of_users.append(user2.uid) # # success, dialog = dialog_holders.create_dialog(list_of_users=list_of_users) # 3. prepare messages msg1 = Message(dialog_id="did_test", text="test from_id=user1.uid", from_id=user1.uid, time_stamp=-1) msg2 = Message(dialog_id="did_test", text="text from_id=user2.uid", from_id=user2.uid, time_stamp=-2) msg3 = Message(dialog_id="did_test", text="text from_id=user2.uid 2", from_id=user2.uid, time_stamp=-3) # 4. prepare update holders update_holder_u1 = UserUpdateHolder(user_id=user1.uid) update_holder_u2 = UserUpdateHolder(user_id=user2.uid) update_holder_u1.add(message=msg1, dialog_id="did_test") update_holder_u1.add(message=msg2, dialog_id="did_test") update_holder_u1.add(message=msg3, dialog_id="did_test") update_holder_u1_dict = update_holder_u1.get_as_dict() update_holder_u2_dict = update_holder_u2.get_as_dict() j_result = update_holder_u1.get_as_json() ##### # this test history_holder_u1 = UserHistoryHolder(user_id=user1.uid) history_holder_u2 = UserHistoryHolder(user_id=user2.uid) for did, dialog_update in update_holder_u1.storage.iteritems(): history_holder_u1.on_add(dialog_update_list=dialog_update) for did, dialog_update in update_holder_u1.storage.iteritems(): history_holder_u2.on_add(dialog_update_list=dialog_update) history_holder_u1_dict = history_holder_u1.to_dict() history_holder_u2_dict = history_holder_u2.to_dict() print "[test_user_history_holder] test cases finished" pass # todo: automate validation
def add_new_user(name, email, password): new_user = User(name=name, email=email, password=password, time=datetime.datetime.now()) db.session.add(new_user) db.session.commit()
def populateDB(): """ For testing and debugging purposes """ Config.load_config() task1 = Task(None, 1, "Make full maps", "Map variables and create relations table with foreign keys", None) task1.save() task2 = Task(None, 1, "Make coffee", "make coffee and drink it", None) task2.save() task3 = Task(None, 1, "Buy present", "buy present for april", None) task3.save() container1 = TasksContainer(None, 1, "todo") container1.add_task(task2, task3) container1.save() container2 = TasksContainer(None, 1, "testing") container2.add_task(task1) container2.save() container3 = TasksContainer.get_by_id(container1._id) container3.print_container() task3.detail = "Updated details" task3.save() container3._name = "Updated name" container3.save() user = User(None, 'admin', 'admin', '*****@*****.**', True) user.save()
def register(username, email): user = User(username, email) db.session.add(user) db.session.commit() saved_user_list = User.query.filter_by(username=user.get_username(), email=email).all() return saved_user_list[len(saved_user_list) - 1]
def post(self): """ Sign-up API The body should be a JSON dictionary including the following attribute(s): - `username`: `str` - `real_name`: `str` - `password`: `str` - `id_card`: `str` - `phone_number`: `str` - `email`: `str` **return**: A JSON dictionary with values: - `code`: `int`, equals to 0 if sign-up is successful - `error`: `str`, shown if `code != 0` """ session = DBSession() try: body = request.get_json() if session.query(User).filter( User.username == body.get('username')).first() is not None: return jsonify(error='Username already exists', code=406) new_user = User(**body) new_user.hash_password() session.add(new_user) session.commit() return jsonify(code=0) except: session.rollback() return jsonify(code=10, error='Unexpected error when creating user') finally: session.close()
def login(): user = User() login = request.form.get('login') password = request.form.get('password') user_data = user.query.filter( User.user_name == login ).first() if not user_data: return render_template( 'login.tmpl', login='******', nav_get_parents=nav_get_parents(), ) if user.check_user_pass(user_id=user_data.id, password=password): render = render_template('login.tmpl', login=login, nav_get_parents=nav_get_parents(),) #resp = make_response(render) #resp.set_cookie('username', user_data.user_name) session['username'] = user_data.user_name session['user_id'] = user_data.id return redirect(request.referrer) or redirect(url_for('index')) else: return render_template( 'login.tmpl', login='******', nav_get_parents=nav_get_parents(), )
def profile(user_id=None): username = session.get('username') session_user_id = session.get('user_id') owner=False if not user_id: user_id = session_user_id edit = False user = User() user_data = user.query.filter( User.id == user_id ).first() if session_user_id == user_id: edit_raw = request.args.get('edit', 'False') if edit_raw.capitalize() == 'True': edit = True owner=True if request.form: update_profile(user_data=user_data, update_form=request.form) return render_template( 'user_profile.tmpl', username=username, user_data=user_data, owner=owner, edit=edit, nav_get_parents=nav_get_parents(), )
def route_register_user(): uid = request.headers.get("uid", None) phone = request.form.get("phone", None) sms_code = request.form.get("sms_code", None) sms_token = request.form.get("sms_token", None) proof = verify_sms_token(sms_token, phone, sms_code) if not proof: abort(401) if not phone: raise ValueError("phone is required value to create an user.") user = User.objects(uid=uid).first() if not user: user = User(uid=uid, phone=phone, status=User.Status.OPENED, available=False, last_login_at=pendulum.now().int_timestamp) user.save() alarm = Alarm(owner=user, records=[]) alarm.save() response = encode(user.to_mongo()) return Response(response, mimetype="application/json")
def register(): if not current_user.is_active(): to_page = request.args.get("next") if to_page == url_for("logout"): to_page = False form = RegistrationForm() if form.is_submitted(): if form.validate(): try: db.session.add(User(form.email.data, form.username.data, form.password.data, form.name.data, form.phone.data)) db.session.commit() flash("Congratualtions, " + (form.name.data or form.username.data) + "! You have registered\ successfully!", "success") return redirect(to_page or url_for("index")) except: if not app.debug: flash("We're sorry, we were unable to register you.\ Feel free to try again.", "error") else: raise else: for key, msg in form.errors.items(): flash("Could not validate " + key + ": " + ", ".join(msg), "error") return render_template("register.html", form=form) else: flash("You are already logged in!", "info") return redirect(request.args.get("next") or url_for("index"))
def user_new(): """create new user""" raw_dict = request.get_json(force=True) try: user_schema.validate(raw_dict) user_dict = raw_dict['data']['attributes'] user = User(user_dict['username'], user_dict['email']) user.add(user) query = User.query.filter_by(email=user_dict['email']).first() print query results = user_schema.dump(query).data print results return jsonify({"id": query.id}) except ValidationError as err: resp = jsonify({"error": err.messages}) resp.status_code = 403 return resp except SQLAlchemyError as e: db.session.rollback() resp = jsonify({"error": str(e)}) resp.status_code = 403 return resp
def post(self): """ Cria um novo usuário --- parameters: - name: nome in: body type: string required: true default: { 'nome': 'any_name'} responses: 201: description: Retorna um usuario baseado no nome schema: id: User properties: message: type: string 400: description: Se ocorrer qualquer erro """ try: dados = request.json user = User(name=dados['nome']) user.save() response = { 'id': user.id, 'nome': user.name, } except: response = {'message': 'erro verifique os campos'} return response, 400 return response, 201
def test_insert_default_user(self): man = dict( uid='GxM4qD1jPMUo80TrrGHx9JI4OnO2', nick_name='mock_user_1', sex='F', birthed_at=1597509312, height=181, body_id=1, occupation="LAWER", education="UNIVERSITY", religion_id=2, drink_id=1, smoking_id=2, blood_id=1, r_token='cPFFTaZTQ2ivAN-bAmxNI5:APA91bFsgmm', latitude=37.5058080, longitude=127.0936859, introduction='hello mock_user_1', joined_at=1597509312, last_login_at=1597509312, user_images=[ dict(index=0, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/GxM4qD1jPMUo80TrrGHx9JI4OnO2_0_c185da2c-ead5-11ea-9038-907841698cfa"), dict(index=1, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/GxM4qD1jPMUo80TrrGHx9JI4OnO2_1_e747faf6-ead5-11ea-9038-907841698cfa"), dict(index=2, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/GxM4qD1jPMUo80TrrGHx9JI4OnO2_2_ef52e4c2-ead5-11ea-9038-907841698cfa"), dict(index=3, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/GxM4qD1jPMUo80TrrGHx9JI4OnO2_3_f549d804-ead5-11ea-9038-907841698cfa"), dict(index=4, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/GxM4qD1jPMUo80TrrGHx9JI4OnO2_4_fc555c36-ead5-11ea-9038-907841698cfa"), dict(index=5, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/GxM4qD1jPMUo80TrrGHx9JI4OnO2_5_0953235a-ead6-11ea-9038-907841698cfa") ], charm_ids=[3, 4, 5, 7, 8, 9], ideal_type_ids=[1, 5, 7, 11, 13], interest_ids=[1, 3, 6, 13]) woman = dict( uid='W56U9v84nfXiM842el1EWgENuzo1', nick_name='mock_user_2', sex='M', birthed_at=1597509312, height=181, body_id=1, occupation="LAWER", education="UNIVERSITY", religion_id=2, drink_id=1, smoking_id=2, blood_id=1, r_token='bAmxNI5:APA91bFsgmm-cPFFTaZTQ2ivAN', latitude=35.1234, longitude=127.987, introduction='hello mock_user_2', joined_at=1597509312, last_login_at=1597509312, user_images=[ dict(index=0, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/W56U9v84nfXiM842el1EWgENuzo1_0_9280f814-ead6-11ea-9038-907841698cfa"), dict(index=1, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/W56U9v84nfXiM842el1EWgENuzo1_1_999790cc-ead6-11ea-9038-907841698cfa"), dict(index=2, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/W56U9v84nfXiM842el1EWgENuzo1_2_a3a38abc-ead6-11ea-9038-907841698cfa"), dict(index=3, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/W56U9v84nfXiM842el1EWgENuzo1_3_920579c2-ead7-11ea-8b30-907841698cfa"), dict(index=4, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/W56U9v84nfXiM842el1EWgENuzo1_4_9ae50bf2-ead7-11ea-8b30-907841698cfa"), dict(index=5, url="https://storage.googleapis.com/pingme-280512.appspot.com/user_images/W56U9v84nfXiM842el1EWgENuzo1_5_a475a41a-ead7-11ea-8b30-907841698cfa") ], charm_ids=[6, 7, 9], ideal_type_ids=[1, 3, 9], interest_ids=[2, 3, 7]) User(**man).save() User(**woman).save()
def get_user(self, id=None): new_user = User(username='******', email='email', created=dt.now(), bio="In West Philadelphia born n raised...", admin=False) app.db.session.add(new_user) # Adds new User record to database app.db.session.commit() # Commits all changes return {'hello': 'world'}
def save_user(db_session, user): user_to_save = User( email=user['email'], username=user['username'], password=user['password'], ) db_session.add(user_to_save) db_session.commit() return user_to_save
def register(): user_ins = json.loads(request.data) is_name_taken = User.get_by_username(user_ins["username"]) is not None if not is_name_taken: new_user = User(None, user_ins["username"], user_ins["password"], user_ins["email"], False) new_user.save() session["username"] = user_ins["username"] return new_user.to_json() else: return redirect(url_for("login_page"))
def createUser(s, data): duplicate_username = s.query(User).filter_by( username=data.get('username')).one_or_none() if duplicate_username: raise ControllerError("Ya existe usuario: '" + data.get('username') + "'") new_user = User(**data) s.add(new_user) s.commit() return "Se creó satisfactoriamente!"
def simple_show(): with session_scope(sql_db.session()) as session: # 清表 session.query(User).delete() # 增 dic1 = {"name": "Adward", "age": 18} dic2 = {"name": "Dragon", "age": 18} session.add(User(**dic1)) session.add(User(**dic2)) # 删 session.query(User).filter(User.name == "Dragon").delete() # 改 session.query(User).filter(User.name == "Adward").update({"age": 17}) # 查 result = session.query(User).all() print([ each.__dict__ for each in result if each.__dict__.pop("_sa_instance_state") ])
def test_user_holders(self): user_holder = UsersHolder() user1 = User(uid="test0", name="test0", secret="1111") user2 = User(uid="test1", name="test1", secret="1111") # add user 1 # add user 2 user_holder.add_user(user=user1) user_holder.add_user(user=user2) # get all users success, all_users_dict = user_holder.get_all() assert success assert len(all_users_dict) == 2, "unexpected size" print "[test_user_holders] test case 1 finished" # get specific user success, user_get_1 = user_holder.get_user(uid=user1.uid) assert success, "user_uid not found" assert user1.uid == user_get_1.uid print "[test_user_holders] test case 2 finished" # update some user user1.icon = "wakawaka" user_holder.update_user(user=user1) success, user_get_1 = user_holder.get_user(uid=user1.uid) assert success, "user_uid not found" assert user1.uid == user_get_1.uid and user_get_1.icon == user1.icon, "not equal" print "[test_user_holders] test case 3 finished" # remove one user remove_success, info = user_holder.remove_user(user_uid=user2.uid) get_success, all_users_dict = user_holder.get_all() assert remove_success assert len(all_users_dict) == 1, "unexpected size" print "[test_user_holders] test case 4 finished"
def test_update_history_manager(self): # 1. create users user1 = User(uid="uid_test0", name="name test0", secret="secr1111") user2 = User(uid="uid_test1", name="name test1", secret="secr1111") dialog_holders = DialogsHolders.get_instance() list_of_users = list() list_of_users.append(user1.uid) list_of_users.append(user2.uid) success, dialog = dialog_holders.create_dialog(list_of_users=list_of_users) assert success assert len(dialog.list_of_users) == len(list_of_users) update_history_manager = UpdateHistoryManager(dialogs_holder=dialog_holders) # 3. prepare messages msg1 = Message(dialog_id=dialog.did, text="test from_id=user1.uid", from_id=user1.uid, time_stamp=-1) msg2 = Message(dialog_id=dialog.did, text="text from_id=user2.uid", from_id=user2.uid, time_stamp=-2) msg3 = Message(dialog_id=dialog.did, text="text from_id=user2.uid 2", from_id=user2.uid, time_stamp=-3) success_msg1, info_msg1 = update_history_manager.on_new_msg(msg=msg1) success_msg2, info_msg2 = update_history_manager.on_new_msg(msg=msg2) success_msg3, info_msg3 = update_history_manager.on_new_msg(msg=msg3) assert success_msg1, info_msg1 assert success_msg2, info_msg2 assert success_msg3, info_msg3 history_before_u1 = update_history_manager.on_get_history_json(user1.uid, dialog_id=dialog.did) history_before_u2 = update_history_manager.on_get_history_json(user2.uid, dialog_id=dialog.did) updates_u1 = update_history_manager.on_get_update_json(user_id=user1.uid) updates_u2 = update_history_manager.on_get_update_json(user_id=user2.uid) history_after_u1 = update_history_manager.on_get_history_json(user1.uid, dialog_id=dialog.did) history_after_u2 = update_history_manager.on_get_history_json(user2.uid, dialog_id=dialog.did) print "[test_update_history_manager] test cases finished" pass
def check_auth(success_runnable, headers): try: decoded = jwt_util.decode_token(encoded_payload=headers['token']) if isinstance(decoded, dict): return success_runnable(User(_dict=decoded)) else: response = json.dumps({'error': 'wrong token'}) return response, 401 except KeyError: response = json.dumps({'error': 'login required'}) return response, 401
def save_user(db_session, user): user_to_save = User( userid=user['roleid'], useraccount=user['userid'], serverid=user['serverid'], level=user['lev'], prof=user['prof'], sex=user['sex'], ) db_session.merge(user_to_save) db_session.commit() return user_to_save
def create_user(): DBSession = sessionmaker(bind=engine) db = DBSession() if not db.query(User).first(): user = User( email='*****@*****.**', username='******', password='******', ) db.add(user) db.commit()
def insert_user( self, user ): # 입력값 : { "user_id" : "example_id", "user_pw" : "hashed_pw" } _user = User(user['user_id'], user['user_pw']) # 사용자 데이터 생성 try: self.db.session.add(_user) # INSERT self.db.session.commit() # COMMIT except Exception as e: # Error 발생할 경우 print("INSERT_USER 실패 :", user) print(e) return False return True
def signIn(): if current_user.is_authenticated: return redirect(url_for("index")) form = SignUpForm() 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("Congrats you successfully created your account, please login") return redirect(url_for("login")) return render_template("signIn.html", form=form)
def create_user(): id_token = request.headers.get("id_token", None) decoded_token = auth.verify_id_token(id_token) uid_to_verify = decoded_token['uid'] uid = request.headers.get("uid", None) if uid_to_verify != uid: raise Exception("Illegal verify_id_token found.") user = User.objects(uid=uid).first() if not user: user = User( uid=uid, status=OPENED, available=False).save() Alert(owner=user, records=[]).save() return Response( user.to_json(), mimetype="application/json")
def signup(): # name= request.json['name'] # email=request.json['email'] # age=request.json['age'] # password=request.json['password'] dataBase.create_all() # hashed_password = generate_password_hash(request.json['password'], method='sha256') new_user = User(name=request.json['name'], email=request.json['email'], public_id=str(uuid.uuid4()), age=request.json['age'], password=request.json['password']) print(new_user) dataBase.session.add(new_user) dataBase.session.commit() dataBase.session.close() resp = jsonify({"Response": 'User Added Successfully', "username": ""}) resp.status_code = 200 return resp
def create_user(u_name, u_dob, u_gender, u_contact, u_aadhar, u_address, u_emergency): # creates new user in database new_user = User(u_name, u_dob, u_gender, u_contact, u_aadhar, u_address, u_emergency) check_str = new_user.check_validity() if check_str == "ok": try: db_user.insert_one(new_user.__dict__) new_user.create_path_file() return new_user.Name + " created with Id " + new_user.AadharNo except errors.DuplicateKeyError as e: return str("Duplicate Data........") except errors.PyMongoError as e: return str(e) except Exception as e: return str(e) else: print(check_str) return "Failed to create user"
def register(request): if request.method == 'POST': data = json.loads(request.body) username = data['username'] password = data['password'] try: user = User.objects.get(username=username) '''if user.password != '' or user.realname != '': return JsonResponse(message_response(2)) # 2 already exists an account with the same username if username != '': user.username = username if password != '': user.password = password user.save()''' response = {'status': 0} #0 catch something error except Exception as e: print e user = User(username=username, password=password) user.save() response = message_response(1) # success return JsonResponse(response)
def add_user(first_name, last_name, email, phone=None): return User(first_name=first_name, last_name=last_name, email=email, phone=phone)