class TestUserApiRetrieve(APITestCase): def setUp(self): self.user = User(first_name='Etienne',last_name='Chabert',email='*****@*****.**',password='******',date_of_birth='1990-11-18') self.user.save() def test_user_valid_token(self): token = self.user.get_valid_token() data = { 'token' : token.token.__str__() } response = self.client.post('/api/users/retrieve',data) self.assertEqual(response.status_code, 200) def test_user_expired_token(self): token = self.user.get_valid_token() token.creation_dateTime -= timedelta(days=42) token.save() data = { 'token' : token.token.__str__() } response = self.client.post('/api/users/retrieve',data) self.assertEqual(response.status_code, 400) def test_user_unknown_token(self): data = { 'token' : uuid.uuid4() } response = self.client.post('/api/users/retrieve',data) self.assertEqual(response.status_code, 400)
def get(self, username=None): response = {} if username: user = User.objects(username__iexact=username).first() if not user: abort(404, message="Username does not exist.") response = { 'username': user.username, 'email': user.email, 'type': user.user_type, 'created_at': str(user.created_at), 'updated_at': str(user.updated_at) } else: users = User.objects() for index, user in enumerate(users): response[index + 1] = { 'username': user.username, 'email': user.email, 'type': user.user_type, 'created_at': str(user.created_at), 'updated_at': str(user.updated_at) } return response
def add_user(name, birthday, phone, pushtoken, photo=None, phone_model=None): user = User(name, birthday, phone, pushtoken, phone_model) db.session.add(user) db.session.commit() if photo is not None: user.photo = func.get_user_photo_path(user.id) db.session.commit()
def register_user(request): try: username = request.GET["username"] except KeyError: return HttpResponseBadRequest("username required but not provided") u = User(username=username) u.save() return HttpResponse(user_json(registered=True))
def setUp(self): self.app = create_app("test_config") self.ctx = self.app.app_context() self.ctx.push() db.drop_all() db.create_all() u = User(username=self.default_username, password=self.default_password) db.session.add(u) db.session.commit() self.client = TestClient(self.app, u.generate_auth_token(), "")
def post(self): args = parser.parse_args() user = User.objects(username__iexact=args['username']).first() if user: abort(409, message="Username already exists.") user = User(username=args['username']) user.password = bcrypt.generate_password_hash(args['password']) if args['type'] == 'individual': user.user_type = args['type'] user.user_profile = Individual() elif args['type'] == 'group': user.user_type = args['type'] user.user_profile = Group() user.save() response = { 'username': user.username, 'email': user.email, 'type': user.user_type, 'created_at': str(user.created_at), 'updated_at': str(user.updated_at) } return response
def adduser(username): u"""Adds user to the REST API""" from getpass import getpass password = getpass() password2 = getpass(prompt='Confirm: ') if password != password2: sys.exit('Sorry, passwords are not matching.') db.set(username, username) user = User(username=username) user.password = password print("User {} is correctly created.".format(username))
def post(self): req_kwargs = self.reqparse.parse_args() user = User(email=req_kwargs['email']) user.hash_password(req_kwargs['password']) try: user.save() except ValidationError as e: return {'message': e.message}, status.HTTP_400_BAD_REQUEST except NotUniqueError: return {'message': 'This email already registered'}, status.HTTP_409_CONFLICT return {'message': 'Success'}, status.HTTP_200_OK
def users_post(): email = request.form['email'] password = request.form['password'] info = request.form['info'] if email is None or password is None: abort(400) if User.query.filter_by(email=email).first() is not None: abort(400) user = User(email=email, info=info) user.hash_password(password) user.registered_on = datetime.utcnow() db.session.add(user) db.session.commit() return jsonify({'status': 'OK', 'user': user.email, 'pass': password})
def create_user(self, author, user, passhash, user_root): u = User() u.author = author u.user_root = user_root u.active = True u.name = user u.password = passhash u.save()
def create_user(): j = request.get_json() u = User(first_name=j['first_name'], last_name=j['last_name'], username=j['username'], role=j['role']) # Hash password # This is not a secure way at all to do this... u.password_hash = hashlib.sha256(j['password'].encode()).hexdigest() db_session.add(u) db_session.commit() return jsonify(UserSchema().dump(u).data)
def delete(self, project_id, collaborator_id): collaborator = Collaborator.get(collaborator_id) current_user = User.current_user() if current_user.key() != collaborator.user.key(): collaborator.remove() else: self.error(404)
def get_token_validity_status(): """check if the token is still valid. If not return 400. If valid, return new token""" token = request.authorization.username user = User.verify_auth_token(token) if not user: return get_error("token not valid"), 400 else: return jsonify(user_info(user)), 200
def user_add(request): name = request.GET.get('name', '') email = request.GET.get('email', '') context={} """ check if email is correct and name not empty """ if not re.match(r"[^@]+@[^@]+\.[^@]+", email) or name == '': return render(request, 'webapp/user_form.html', context) """ check if user already exists """ try: exists = User.objects.get(email=email) except User.DoesNotExist: exists = None user = User(email = email, name = name) user.save() user_list = User.objects.all().order_by('email') context={"user_list":user_list} return render(request, 'webapp/user.html', context) return render(request, 'webapp/user_form.html', context)
def verify_password(email_or_token, password): user = User.verify_auth_token(email_or_token) if not user: # try to authenticate with username/password user = User.query.filter_by(email=email_or_token).one() if not user or not user.verify_password(password): return False g.user = user return True
def post(self, request): data = json.loads(request.body) form = UserForm(data) if form.is_valid(): user = User.create(**form.cleaned_data) data = {'user': user.to_dict()} else: data = {'error':form.errors} return render_json_response(request, data)
def get(self, request, *args, **kwargs): csrf_token = get_token(request) id = kwargs.get('id') user = User.get_by_pk(id) if user is None: data = {'user': {}, 'csrf_token': csrf_token} else: data = {'user': user.to_dict(), 'csrf_token': csrf_token} return render_json_response(request, data)
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.drop_all() db.create_all() user = User( username="******", email="*****@*****.**", ) user.hash_password("chiditheboss") db.session.add(user) db.session.commit() g.user = user self.client = self.app.test_client()
def put(self, request, *args, **kwargs): id = kwargs.get('id') data = json.loads(request.body) form = UserForm(data) if form.is_valid(): user = User.update(id, form.cleaned_data) data = {'event': user.to_dict()} else: data = {'error': form.errors} return render_json_response(request, data)
def login(): params = request.json access_token = params.get('accessToken') fb_id = params['fbId'] user = get_user(fb_id, by_fb_id=True) if user is None: if access_token is None: raise APIException('please provide accessToken', 400) else: if not facebook.verify(fb_id, access_token): raise APIException("access token invalid", 403) user = User(fb_id=fb_id, access_token=access_token, fullname=params['fullName'], image_link=params['imageLink'], badge_setting=params.get('badgeSetting'), device_token=params.get('deviceToken'), badge_num=0, claimed=True) db.session.add(user) db.session.commit() else: if access_token is None: assert_user_is_unclaimed(user) else: if not facebook.verify(fb_id, access_token): raise APIException("access token invalid", 403) if user.claimed == False: user.claimed = True db.session.add(user) db.session.commit() if login_user(user, remember=True): session.permanent = True return jsonify(user.dictify()) # Why would this happen? raise APIException('could not log in', 400)
def post(self, request): check = CheckRequest(request); if check.user: return JsonResponse({ "status": "error", "msg": "User logined" }) uf = UserForm(check.jsonForm) if uf.is_valid(): #检测用户是否存在 checkUser = User.objects.filter(qq__exact = uf.cleaned_data['qq']).first() if checkUser: if checkUser.status == 0: return JsonResponse({ "status" : 'error', 'msg' : "此qq账户已注册,但未激活" }) else: return JsonResponse({ "status" : 'error', 'msg' : "此qq账户已存在" }) user = User( username = uf.cleaned_data['username'], password = db_password(uf.cleaned_data['password']), qq = uf.cleaned_data['qq'], login_random = new_random(), activate_random = new_random(), recover_random = new_random() ) user.save() return JsonResponse({ "status" : 'success', 'msg' : "" }) else: return JsonResponse({ "status" : 'error', 'msg' : "Illegal post" })
def verify_token(token, useless): """ Verify if the token is valid then get the user associated with this token. The fetched user is then put in global context. """ user = User.verify_auth_token(token) if not user: return False g.user = user return True
def POST_users(request, format): """ Respond to the "POST users" request. We create a new user and log them in. """ # Get the request parameters. params = apiHelper.get_params(request, resource_name="user") error = apiHelper.check_params(params, required_params=[], optional_params=["username", "password"]) if error != None: return error username = params.get("username") password = params.get("password") if username == "": username = None if password == "": password = None # Check that the given username doesn't already exist. if username != None: if User.objects.filter(username=username).exists(): return HttpResponseBadRequest("Duplicate User") # Create a new User object for this user. user = User() user.username = username if password != None: user.set_password(password) user.created_at = datetime.datetime.now() user.updated_at = datetime.datetime.now() user.save() # Open up a session for this new user. token = session.create(user) # Finally, return the newly-created user and the login token back to the # caller. return apiHelper.response({'user' : user.to_dict(), 'token' : token}, format=format, status=HTTP_RESPONSE_POST_OK)
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() user = User( username="******", email="*****@*****.**", password_hash="chiditheboss" ) user.hash_password("chiditheboss") db.session.add(user) db.session.commit() g.user = user bucketlist = Bucketlist(name="Awesome Bucketlist", created_by=g.user.id) bucketlist.save() self.client = self.app.test_client()
def post(self): args = auth_parser.parse_args() username = args['username'] password = args['password'] user = User.objects(username__iexact=username).first() if user: if bcrypt.check_password_hash(user.password, password): return {'Success': 'User authenticated.'} return {'Error': 'Invalid username or password.'}, 401
def post(self): data = json.loads(self.request.body) current_user = User.current_user() project = Project( name=data.get('name'), note=data.get('note')) project.put() collaborator = Collaborator( project=project, user=current_user, is_manager=True) collaborator.put() self.response.write(json.dumps(project.to_dict()))
def delete(self, username): if not username: abort(404, message="A username is required.") user = User.objects(username__iexact=username).first() if not user: abort(404, message="Username does not exist.") user.delete() response = {'message': 'deleted'} return response
def get(self, username): if not username: abort(404, message="A username is required.") user = User.objects(username__iexact=username).first() if not user: abort(404, message="Username does not exist.") if user.user_type == 'individual': pass else: pass
def classic_registration(): data = get_data(request) username = data.get('username') password = data.get('password') token_duration = data.get('duration') if not username or not password: return get_error("username, password must be provided"), 400 if User.query.filter_by(username=username).first() is not None: logger.info("username:%s is already used", username) return get_error("existing user"), 409 # existing user logger.info("create classic user, username:%s", username) # create and save new user to db user = User(username=username) user.create(password) if token_duration: token_duration = int(token_duration) return jsonify(user_info(user, token_duration)), 201 else: return jsonify(user_info(user)), 201
def get(self): logger.debug('GET: %s' % request.args) response = self._get_token() logger.debug('Google Response: %s' % response) data = self._get_data(response) logger.debug('Google Data: %s' % data) user = User.get_or_create(data) login_user(user) logger.debug('User Login: %s' % user) #return redirect(request.args.get('state') or url_for('index')) return jsonify({"success":"true"})
def user(user_record): return User(**user_record)
from api.models import User, NetWorthLeaderboard, Stock # --------------------------------------- USERS ----------------------------------------------------- # User(username, email, country, current_balance, user_type, current_net_worth) user_seed_list = [] user_seed_list.append(User('vinit', '*****@*****.**', 'Canada', 100, 1, 100)) user_seed_list.append(User('bobby', '*****@*****.**', 'Canada', 200, 1, 200)) user_seed_list.append(User('ryan', '*****@*****.**', 'Canada', 250, 1, 250)) user_seed_list.append(User('john', '*****@*****.**', 'Canada', 300, 1, 300)) user_seed_list.append(User('gary', '*****@*****.**', 'Canada', 110, 1, 110)) user_seed_list.append(User('jerry', '*****@*****.**', 'Canada', 220, 1, 230)) user_seed_list.append(User('jimmy', '*****@*****.**', 'Canada', 301, 1, 400)) user_seed_list.append(User('robert', '*****@*****.**', 'Canada', 300, 1, 300)) user_seed_list.append(User('karen', '*****@*****.**', 'Canada', 111, 1, 123)) user_seed_list.append(User('jasmine', '*****@*****.**', 'Canada', 312, 1, 412)) user_seed_list.append(User('hetal', '*****@*****.**', 'Canada', 152, 1, 745)) user_seed_list.append(User('sejal', '*****@*****.**', 'Canada', 24, 1, 152)) user_seed_list.append(User('harry', '*****@*****.**', 'Canada', 152, 1, 285)) user_seed_list.append(User('rahul', '*****@*****.**', 'Canada', 651, 1, 794)) user_seed_list.append(User('david', '*****@*****.**', 'Canada', 846, 1, 1000)) user_seed_list.append(User('salman', '*****@*****.**', 'Canada', 101, 1, 142))
def setUp(self): """Set up the role viewset tests.""" super().setUp() request = self.request_context["request"] user = User() user.username = self.user_data["username"] user.account = self.customer_data["account_id"] request.user = user sys_role_config = { "name": "system_role", "display_name": "system_display", "system": True } def_role_config = { "name": "default_role", "display_name": "default_display", "platform_default": True } self.display_fields = { "applications", "description", "uuid", "name", "display_name", "system", "created", "policyCount", "accessCount", "modified", "platform_default", } with tenant_context(self.tenant): self.principal = Principal(username=self.user_data["username"]) self.principal.save() self.policy = Policy.objects.create(name="policyA") self.group = Group(name="groupA", description="groupA description") self.group.save() self.group.principals.add(self.principal) self.group.policies.add(self.policy) self.group.save() self.sysRole = Role(**sys_role_config) self.sysRole.save() self.defRole = Role(**def_role_config) self.defRole.save() self.defRole.save() self.policy.roles.add(self.defRole, self.sysRole) self.policy.save() self.permission = Permission.objects.create(permission="app:*:*") self.permission2 = Permission.objects.create(permission="app2:*:*") self.access = Access.objects.create(permission=self.permission, role=self.defRole) self.access2 = Access.objects.create(permission=self.permission2, role=self.defRole) self.access3 = Access.objects.create(permission=self.permission2, role=self.sysRole) Permission.objects.create(permission="cost-management:*:*")
def test_create_user(self): user = User(username="******") user.save() db_user = User.objects.get(username=user.username) self.assertEqual(user == db_user, True)
def setUp(self): """Configure test enviroment.""" os.environ['APP_SETTINGS'] = 'Testing' self.patcher = mock.patch( 'api.services.auth.helpers.add_extra_user_info', return_value=(None, None, None)) self.patcher.start() self.app = create_app("Testing") self.app_context = self.app.app_context() self.app_context.push() db.drop_all() db.create_all() # test client self.client = self.app.test_client() token_payloads_list = [ self.incomplete_payload, self.expired_payload, self.test_cio_role_payload, self.test_society_president_role_payload, self.test_auth_role_payload, self.test_finance_payload, self.test_successops_payload ] for token_payload in token_payloads_list: token_payload.update({ 'iss': self.app.config['API_ISSUER'], 'aud': self.app.config['API_AUDIENCE'] }) self.header = { "Authorization": self.generate_token(self.test_user_payload), "Content-Type": "application/json" } self.success_ops = { "Authorization": self.generate_token(self.test_successops_payload), "Content-Type": "application/json" } self.society_president = { "Authorization": self.generate_token(self.test_society_president_role_payload), "Content-Type": "application/json" } self.sparks_society_president = { "Authorization": self.generate_token(self.test_sparks_society_president_payload), "Content-Type": "application/json" } self.society_secretary = { "Authorization": self.generate_token(self.test_society_secretary_payload), "Content-Type": "application/json" } self.cio = { "Authorization": self.generate_token(self.test_cio_role_payload), "Content-Type": "application/json" } self.finance = { "Authorization": self.generate_token(self.test_finance_payload), "Content-Type": "application/json" } self.bad_token_header = { "Authorization": self.generate_token({"I don't know": "what to put here"}), "Content-Type": "application/json" } # test centers self.nairobi = Center(name='Nairobi') self.kampala = Center(name='Kampala') self.lagos = Center(name='Lagos') # test societies self.phoenix = Society(name="Phoenix", color_scheme="#00001", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") self.istelle = Society(name="iStelle", color_scheme="#00002", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") self.sparks = Society(name="Sparks", color_scheme="#00003", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") self.invictus = Society(name="Invictus", color_scheme="#00004", logo="https://bit.ly/2FTjkbV", photo="https://bit.ly/2k2l0qx") # test roles self.successops_role = Role(uuid="-KkLwgbeJUO0dQKsEk1i", name="success ops") self.fellow_role = Role(uuid="-KXGy1EB1oimjQgFim6C", name="Fellow") self.success_role = Role(uuid="-KXGy1EB1oimjQgFim6F", name="success ops") self.finance_role = Role(uuid="-KXGy1EB1oimjQgFim6L", name="finance") self.lf_role = Role(uuid="d47ec8a7-3f09-44a5-8188-ff1d40ef35b6", name="Learning Facilitator") self.president_role = Role(uuid="-KXGyd2udi2", name="society president") self.v_president_role = Role(uuid="-KXGy32odnd", name="vice president") self.secretary_role = Role(uuid="-KXGy12odfn2idn", name="society secretary") self.cio_role = Role(uuid="-KXGionceu24i2y", name="cio") # test cohorts self.cohort_12_Ke = Cohort(name="cohort-12", center=self.nairobi) self.cohort_14_Ke = Cohort(name="cohort-14", center=self.nairobi) self.cohort_12_Ug = Cohort(name="cohort-12", center=self.kampala) self.cohort_1_Nig = Cohort(name="cohort-1", center=self.lagos) # test users self.test_user = User(uuid="-KdQsMt2U0ixIy_-yWTSZ", name="Test User", photo="https://www.link.com", email="*****@*****.**", center=self.lagos, cohort=self.cohort_1_Nig, society=self.phoenix) self.test_user_2 = User(uuid="-KdQsawesome_usedk2cckjfbi", name="Test User2", photo="https://www.link.com", email="*****@*****.**", center=self.kampala, cohort=self.cohort_12_Ug, society=self.sparks) self.test_user_3 = User(uuid="-KdQsawesomb2dunkdnw", name="Test User3", photo="https://www.link.com", email="*****@*****.**", center=self.nairobi, cohort=self.cohort_12_Ke, society=self.invictus) self.test_cio = User( uuid="-KdQdsdadqwdqomb2dunkdnw", name="Test CIO", photo="https://www.link.com", email="*****@*****.**", center=self.nairobi, ) self.test_cio.roles.append(self.cio_role) self.president = User( uuid="-KdQsMtixG4U0y_-yJEH", name="Test President", photo="https://lh6.googleusercontent.com/-1DhBLOJentg/AAAAAAAAA" "AI/AAAAAAnAABc/ImeP_cAI/photo.jpg?sz=50", email="*****@*****.**", center=self.lagos, cohort=self.cohort_1_Nig, society=self.phoenix) self.president.roles.append(self.president_role) self.vice_president = User( uuid="-KdQsMtixGc2nuekwnd", name="Test Vice-President", photo="https://lh6.googleusercontent.com/-1DhBLOJentg/AAAAAAAAA" "AI/AAAAAAnAABc/ImeP_cAI/photo.jpg?sz=50", email="*****@*****.**", center=self.nairobi, cohort=self.cohort_12_Ke, society=self.sparks) self.vice_president.roles.append(self.v_president_role) self.secretary = User( uuid="-Kuty7hryt8cbkc", name="Test Secretary", photo="https://lh6.googleusercontent.com/-1DhBLOJentg/AAAAAAAAA" "AI/AAAAAAnAABc/ImeP_cAI/photo.jpg?sz=50", email="*****@*****.**", center=self.nairobi, cohort=self.cohort_14_Ke, society=self.invictus) self.secretary.roles.append(self.secretary_role) # test ActivityType self.hackathon = ActivityType(name="Hackathon", description="A Hackathon", value=100) self.tech_event = ActivityType(name="Tech Event", description="Organize a tech event", value=2500) self.interview = ActivityType( name="Bootcamp Interviews", description="Interviewing candidate for a fellow" " recruiting event", value=20, supports_multiple_participants=True) # test Activity self.alibaba_ai_challenge = Activity( name='Fashion challenge', activity_type=self.hackathon, activity_date=datetime.date.today() + datetime.timedelta(days=21), added_by=self.president) self.js_meet_up = Activity(name='Nairobi Js meetup', activity_type=self.tech_event, activity_date=datetime.date.today() + datetime.timedelta(days=14), added_by=self.president) self.bootcamp_xiv = Activity(name='Bootcamp XIV Interviews - Nairobi', activity_type=self.interview, activity_date=datetime.date.today() + datetime.timedelta(days=14), added_by=self.president) # test LoggedActivity self.log_alibaba_challenge = LoggedActivity( name="my logged activity", description="Participated in this event", value=2500, user=self.test_user, activity=self.alibaba_ai_challenge, society=self.invictus, activity_type=self.hackathon) self.log_alibaba_challenge2 = LoggedActivity( name="my second logged activity", description="Participated in this event", value=2500, user=self.test_user, activity=self.alibaba_ai_challenge, society=self.sparks, activity_type=self.hackathon) self.redemp_req = RedemptionRequest(name="T-shirt Funds Request", value=2500, user=self.test_user, center=self.test_user.center, society=self.test_user.society) # save common items to db self.tech_event.save() self.interview.save() self.hackathon.save() self.test_user.save()
def signup(): body = request.get_json() User.create_user(body["email"], body["password"]) return jsonify({"message": "registrado!"}), 200
def profile(): current_user_id = get_jwt_identity() user = User.get(current_user_id) return jsonify(user.serialize())
def post_profile(): request_json = request.get_json() current_user_id = get_jwt_identity() current_user = User.get(current_user_id) current_user.update(request_json) return jsonify(current_user.serialize())
def create(self, validated_data): password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() return user
"furui", "たかぽん", "マルコ", "エネル", "ひとみちゃん", "ヤッホー", "さわお", "よーへい", "ユキタ", "ガウディ", "サモトラケのニケ", "クロネッカー", "座敷わらしポンタ", "うさかめ", "やまねこ", ] for i, name in enumerate(userNames): user = User( email=f"vl2id0aow1qkrt{i+1}@nfakdls.com", fund=random.randint(1000000, 30000000), ) user.set_password("dammy") user.save() profile = Profile( name=name, user=user, ) profile.save()