def auth(): if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 email = request.json.get('email', None) password = request.json.get('password', None) if not email: return {"msg": "Please enter an email"}, 400 if not password: return {"msg": "Please enter a password"}, 400 user = User.query.filter(User.email == email).first() if request.method == 'PUT': # login if not user or not user.check_password(password): return {"msg": "Invalid email or password"}, 401 elif request.method == 'POST': # signup if user: return {"msg": "A user with the given email already exists"}, 401 if len(password) < 4: return {"msg": "Password must be 4 characters or longer"}, 401 user = User(email=email) user.password = password db.session.add(user) db.session.commit() access_token = create_access_token(identity=user.to_dict()) return access_token, 200
def disable_register(self, arguments): """ @apiVersion 1.0.0 @api {post} /api/V1/user/disable_register 被禁用户的注册接口 @apiName disable_register @apiGroup User @apiParam {int} mobile 用户手机号 @apiParam {int} company_name 公司名称 """ company_name = arguments['company_name'] mobile = arguments['mobile'] user = User.find_one({'mobile': mobile}) company = Company.find_one({'company_name': company_name}) if company: return self.fail(message=u"该公司已存在") else: params = {'admin': user['uid']} company = Company.create_company(company_name, **params) user['company_id'].append(company['company_id']) result = User.update_one( {'_id': user['_id']}, {'$set': { 'company_id': user['company_id'] }}) if result.raw_result['ok'] == 1: user = load_user(user['uid']) login_user(user, remember=True) return self.done(u"登录成功") else: return self.fail(u"添加失败")
def new_login(self, arguments): """ @apiVersion 1.0.0 @api {post} /api/V1/new_login 用户登录(new) @apiName new_login @apiGroup User @apiParam {int} mobile 用户手机号作为登录用户名 @apiParam {int} code 用户密码 @apiSuccess {String} message y验证结果 """ mobile = arguments['mobile'] verify_code = arguments['code'] user = User.find_one({'mobile': mobile}) if not user: return self.fail(message=u'该用户不存在') if verify_code != int(session[str(mobile)]): return self.fail(message=u'验证码不正确') if user.get('company_id') and len(user['company_id']) != 0: user = load_user(user['uid']) login_user(user, remember=True) return self.done(User.user_find_one({'mobile': mobile})) else: return self.fail(u"用户没有公司,请先创建公司")
def register(): if request.method == "POST": try: account = request.form["account"] username = request.form["username"] password = request.form["password"] user = User() user.createUser( account=account, password=generate_password_hash(password), role="USER_LOW", username=username, ) db.session.add(user) db.session.commit() baseLink = BaseUser() baseLink.createInfo(level=1, userAc=account) db.session.add(baseLink) db.session.commit() except Exception as e: print(e) flash("注册失败") return redirect(url_for("auth.register")) return redirect(url_for("auth.login")) else: return render_template("auth/register.html")
def join_party(request): if is_party_assigned(request): return redirect('player') if request.method == 'POST': form = JoinPartyForm(request.POST) if form.is_valid(): party_tag = form.cleaned_data['party_tag'] party = Party.objects.get(tag=party_tag) password = form.cleaned_data['admin_password'] user = get_user(request) if not user: user = User(session=Session.objects.get(session_key=request.session.session_key), party=party) else: user.party = party user.save() if password != '' and password == party.password: party.admins.add(user) party.save() return redirect('player') else: form = JoinPartyForm() return render(request, 'party/join_party.html', {'join_party_form': form})
def addUser(): if request.method == "POST": try: account = request.form["account"] username = request.form["username"] password = request.form["password"] level = request.form["level"] if level == "MANAGE_LOW": user = User() user.createUser( account=account, password=generate_password_hash(password), role=level, username=username, ) db.session.add(user) db.session.commit() sha = hashlib.md5() sha.update(account.encode("utf-8")) loveworker = LoveWorker() loveworker.id = sha.hexdigest() loveworker.level = 8 loveworker.manId = g.user.manLink.first().id loveworker.userAc = account db.session.add(loveworker) db.session.commit() except Exception as e: flash("用户已存在") return redirect(url_for("manage.index")) else: user = g.user return render_template("manage/user/add.html", user=user)
def testid_register(testid): """ Given the user's personal info, return a token representing the user. This token should be stored in a session cookie on the frontend side. """ form = request.form # Create the user and add data testid = TestID.query.filter_by(testid=testid).first() if not testid: return "Test ID Not Found", 400 try: user = User() user.token = str(uuid.uuid4()) user.testid = testid user.reuse = False user.first_name = form["firstname"] user.last_name = form["lastname"] user.email = form["email"] user.date_of_birth = form["date-year"] + "-" + form[ "date-month"] + "-" + form["date-day"] user.testing_location = form["testing-location"] db.session.add(user) db.session.commit() except KeyError as e: print(form) print(e) return "Missing field", 400 # Send back le token return user.token
def authorized(): resp = rc.authorized_response() if resp is None: raise AuthorizationFailed( 'Error: {} ({})'.format( request.args['error'], request.args['error_description'] )) session['rc_token'] = { 'access_token': resp['access_token'], 'refresh_token': resp['refresh_token'], 'expires_at': resp['expires_in'] + time() - 600 } me = rc.get('people/me').data user = User.query.get(me['id']) if user is None: user = User( id=me['id'], name=util.name_from_rc_person(me), avatar_url=me['image'], is_faculty=me['is_faculty']) db.session.add(user) db.session.commit() elif user.faculty != me['is_faculty']: user.faculty = me['is_faculty'] db.session.commit() session['user_id'] = user.id return redirect(url_for('home'))
def add_users(users): for user_data in users.values(): user = User( username=user_data['username'], default_tees=user_data['default_tees'] ) user.set_password('asdf') db.session.add(user) db.session.commit() for _, round_data in user_data['rounds'].items(): course = Course.query.filter_by( nickname=round_data['course'] ).first() course_tee = course.get_tee_by_color(round_data['tee_color']) round_data['user_id'] = user.id round_data['tee_id'] = course_tee.id round_data.update({ 'user_id': user.id, 'tee_id': course_tee.id, 'holes': {h['hole_number']: h for h in round_data['holes'].values()} }) update_round(round_data)
def register(request): if request.method == 'POST': user_id = request.POST['user_id'] client_id = Client(client_id = request.POST['companyTypeSelect']) #ForeignKey prefix = request.POST['appellationTypeSelect'] first_name = request.POST['first_name'] middle_name = request.POST['middle_name'] last_name = request.POST['last_name'] job_title = request.POST['job_title'] email = request.POST['email'] office_phone = request.POST['office_phone'] cell_phone = request.POST['cell_phone'] if User.objects.filter(user_id = user_id).exists(): messages.info(request, 'User already exists. Please try different User name') return redirect('register') else: user = User(user_id = user_id, client_id=client_id, prefix=prefix, first_name=first_name, middle_name=middle_name, last_name=last_name, job_title=job_title, email=email, office_phone=office_phone, cell_phone=cell_phone) user.save() #messages.info(request, 'User Created. Please login now.') return redirect('/') else: client_list = Client.objects.order_by('client_id') #all client records context = {'client_list' : client_list} return render(request, 'register.html', context)
def login(): if request.method == 'GET': user_dict = request.authorization elif request.method == 'POST': user_dict = request.get_json() if user_dict is None or user_dict is '': return util.make_auth_challenge(msg='No credentials provided') try: username = user_dict['username'] except: return util.make_json_error(msg='Missing username', status_code=401) try: password = user_dict['password'] except: return util.make_json_error(msg='Missing password', status_code=401) if not User.authenticate(username, password): return util.make_json_error(msg='Wrong username and/or password', status_code=401) try: user = User.get_by_name(user_dict['username']) login_user(user) return util.make_json_success(msg='Success') except UserNotFoundError as e: return util.make_json_error(msg='User not found', status_code=401)
def register_user(email: str, password: str, repeat_password: str) -> int: """@ret http status code 200, 409, 422 200 : user created. 409 : username already exist. 422 : something's wrong with your password/ username """ # this shouldn't be here... if not (email and password and repeat_password): abort( 422, description= "Please make sure to include the following params: email, password, repeat_password" ) elif len(password) < 12: abort( 422, description= "Password should be more then 12 characters long and repeat_password should match password" ) elif password != repeat_password: abort(422, description="Password should match repeat password field") elif User.find_user_by_email(email): abort(409, "Username already exist") user = User.create(email, password) if not user: return abort( 500, "The server encountered an unexpected condition which prevented it from fulfilling the request, please try agian later" ) return {"email": email}
def authorized(): resp = rc.authorized_response() if resp is None: raise AuthorizationFailed('Error: {} ({})'.format( request.args['error'], request.args['error_description'])) session['rc_token'] = { 'access_token': resp['access_token'], 'refresh_token': resp['refresh_token'], 'expires_at': resp['expires_in'] + time() - 600 } me = rc.get('profiles/me').data user = User.query.get(me['id']) if user is None: user = User( id=me['id'], name=util.name_from_rc_person(me), avatar_url=me['image_path'], is_faculty=util.profile_is_faculty(me), ) db.session.add(user) db.session.commit() elif user.faculty != util.profile_is_faculty(me): user.faculty = util.profile_is_faculty(me) db.session.commit() session['user_id'] = user.id return redirect(url_for('home'))
def sign_up(): username = request.json.get('username', None) email = request.json.get('email', None) password = request.json.get('password', None) if not username or not password or not email: return jsonify({'login': False}), 401 hashed_pass = generate_password_hash(password, method='sha256') default_skill = json.dumps({'learning':0}) new_user = User(username=username, email=email, hashed_password=hashed_pass, user_skills=default_skill, focus='', theme='galaxy') db.session.add(new_user) db.session.commit() # Create the tokens we will be sending back to the user access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) user = new_user.to_dict() print('---------------------------------------') print(user) # Set the JWT cookies in the response resp = jsonify({'login': True, **user}) print('--------------------') print(resp) set_access_cookies(resp, access_token) set_refresh_cookies(resp, refresh_token) return resp, 200
def normal_register(): request_json = request.get_json() print(request_json) if request_json.get('isSnap'): user = User(email="*****@*****.**", password="******", name=request_json['name'], isSnap=True, snapPic=request_json['snapPic']) db.session.add(user) db.session.commit() return json.dumps({'id': user.id, 'status': 0}) if User.query.filter_by(email=request_json['email']).first(): return json.dumps({ 'status': 1, 'output': User.query.filter_by(email=request_json['email']).first().email, 'error': "User Already Exists" }) email = request_json['email'] hashed_pwd = bcrypt.generate_password_hash( request_json['password']).decode('utf-8') name = request_json['name'] # noinspection PyArgumentList user = User(email=email, password=hashed_pwd, name=name) db.session.add(user) db.session.commit() return json.dumps({'id': user.id, 'status': 0})
def test_create_new_user(new_user): """Test user model.""" new_user = User(username=new_user["username"], password=new_user["password"]) assert new_user.username == "TestName" assert new_user.check_password("TestPassword")
def test_create_new_user(new_user): """Test user model.""" new_user = User(username=new_user['username'], password=new_user['password']) assert new_user.username == 'TestName' assert new_user.check_password('TestPassword')
def add_user_to_db(username: str, password: str) -> bool: user_check = User.query.filter_by(username=username).first() if user_check is not None: return False user = User(username=username) user.set_password(password) db.session.add(user) session_commit() return True
def create_user(self, arguments): user_exist = User.find_one(mobile=arguments['mobile']) if user_exist: return self.is_fail('当前手机号码已被注册') if arguments['verify_code'] != session[str(arguments['mobile'])]: return self.is_fail('验证码不正确') user = User(arguments['mobile'], arguments['password1']) result = user.save() return self.is_done(result)
def post(self): data = request.get_json()['data'] newuser = User() newuser.user = data['user'] newuser.password = data['password'] newuser.rol = '1' db.session.add(newuser) db.session.commit() return {"data": data}, 201
def create_user(): # TODO: Make jwt user id based to expire user session if permissions are changed identity = get_jwt_identity() request_user = User.query.filter_by(username=identity["username"]).first() is_admin = True if request_user.role.role == "admin" else False if is_admin == False: return jsonify(message="Unauthorized access!"), 401 if not request.is_json: return jsonify(message="Missing JSON in request"), 400 username = request.json.get("username", None) password = request.json.get("password", None) role_id = request.json.get("role", None) if not username: return ( jsonify(message="Please provide your username!", type="USERNAME_MISSING"), 400, ) if not password: return ( jsonify(message="Please provide your password!", type="PASSWORD_MISSING"), 400, ) if not role_id: return (jsonify(message="Please provide your role!", type="ROLE_MISSING"), 400) if role_id not in ["1", "2"]: return ( jsonify(message="Please assign correct role!", type="ROLE_INCORRECT"), 400, ) try: user = User(username=username, role_id=role_id) user.set_password(password) db.session.add(user) db.session.commit() db.session.refresh(user) except Exception as e: if type(e) == sa.exc.IntegrityError: app.logger.info(f"User {username} already exists!") return (jsonify(message="User already exists!", type="DUPLICATE_USER"), 409) app.logger.error("Error creating user") app.logger.error(e) return jsonify(message="Error creating user!"), 500 return jsonify(user_id=user.id, message="User has been created!"), 201
class BaseTestCase(unittest.TestCase): def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.user = User(email="*****@*****.**", password="******") self.user.put() def tearDown(self): self.testbed.deactivate()
def resolve_user(self, args, **kwargs): id = kwargs.get('id') email = kwargs.get('email') if id: return User.objects(pk=id).first() elif email: return User.objects(email=email).first() else: raise Exception('Mala consulta!')
def dataCollected(request, argument): values = argument.split("Z") entry = User(name=values[0], email=values[2], password=values[1], validation=values[0] + values[1]) entry.save() username = entry.name email = entry.email context = {'username': username, 'email': email} return render(request, 'backend/profile.html', context)
def add_user(request): response = {} try: user = User(username=request.GET.get('username')) user.save() response['msg'] = 'success' response['status'] = 200 except Exception as e: response['msg'] = str(e) response['status'] = 0 return JsonResponse(response)
def register(request): data = request.POST existing_user = User.objects.filter(username=data.get("username")) if existing_user.count() == 0: user = User(username=data.get("username"), password=data.get("password")) user.save() user_serialised = {"username": user.username, "password": user.password, "id": user.id} output_json = simplejson.dumps(user_serialised) else: output_json = simplejson.dumps({"success": False}) return HttpResponse(output_json, mimetype='application/json')
def get_attendees(event_id, attendee_type): user_id = auth.check_token(request.headers.get('session')) if not user_id: return "Unauthorized request: Bad session token", 401 user = Organizer.find_id(user_id) if not user: return "Unauthorized request: User doesn't have permission", 401 if not event_id: return "Event ID required", 400 event = Event.find_event(event_id) if not event: return "Event not found", 404 attendee_type = attendee_type.lower() if attendee_type not in ['attendees', 'students', 'mentors', 'organizers']: return "Invalid Attendee Type", 404 attendees = None if attendee_type == 'attendees': attendees = { 'students': [], 'mentors': [], 'organizers': [], 'checkins': [] } for usr in User.objects(events=event.id): if usr.type in ['student', 'mentor', 'organizer']: attendees[usr.type + 's'].append(usr.to_dict()) else: if not attendees['other']: attendees['other'] = [] attendees['other'].append(usr.to_dict()) for usr in User.objects(checkins=event.id): attendees['checkins'].append(usr.to_dict()) else: attendees = [] attendee_cls = None if attendee_type == 'students': attendee_cls = Student elif attendee_type == 'mentors': attendee_cls = Mentor elif attendee_type == 'organizers': attendee_cls = Organizer else: attendee_cls = User for usr in attendee_cls.objects(events=event.id): attendees.append(usr.to_dict()) return json.dumps(attendees), 200, jsonType
def mutate(root, info, **kwargs): user = User.objects(email=kwargs.get('email')).first() if not user: raise Exception('El usuario no existe') chat = Chat.objects(users__in=[user]) if chat: raise Exception('Ya hay un chat con el usuario') chat = Chat(users=[User.objects( pk=get_jwt_identity()).first(), user]).save() return CreateChat(chat)
def update_password(): form = request.get_json(True, True) user_id = auth_helper() new_pass = form.get("password") if not new_pass: return jsonify(error="密码不能为空"), 400 new_pass = encrypt_helper(new_pass) User.patch(user_id=user_id, password=new_pass) cookie = request.cookies session_id = cookie.get('fat-wallet') session.pop(session_id) return jsonify(data="ok"), 200
def add_user(request): response = {} try: user = User(username="******") user.save() response['msg'] = 'success' response['error_num'] = 0 except Exception as e: response['msg'] = str(e) response['error_num'] = 1 return JsonResponse(response)
def post(self, request): post_data = dict(request.POST) un = post_data["username"][0] pw = post_data["password"][0] email = post_data["email"][0] user = User.objects.create_user(un, email, pw) user.save() ud = UserData(name=un, email=email) ud.save() user_login = authenticate(username=un, password=pw) login(request, user_login) return HttpResponseRedirect("/")
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() 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 add_company_user(): request_json = request.get_json() auth_token = request_json['auth_token'] user = User.verify_auth_token(auth_token) if user is None: return json.dumps({ 'status': 0, 'error': "Session expired. Please login again." }) elif not user.isMaster: return json.dumps({'status': 0, 'error': "Access Denied"}) company_id = request_json['company_id'] company = Company.query.filter_by(id=company_id).first() name = request_json['name'] designation = request_json['designation'] email = request_json['email'] random_password = ''.join( random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase + string.punctuation, k=8)) msg = Message("Welcome to Helpify Corporate", sender="*****@*****.**", recipients=[email], body=f""" Hi {name}, Thanks for your interest in working with us over the upcoming event! We have created a user account for you under the company {company.name}. You may log in by going to {current_app.config['CURRENT_URL']}. Your username is the email address on which you received this email, and your password is: {random_password} Please feel free to contact us in case of any queries. We look forward towards meeting you at the event! Regards, Helpify Corporate Team (on behalf of the event organizers) """) mail.send(msg) hashed_pwd = bcrypt.generate_password_hash(random_password).decode('utf-8') new_user = User(name=name, email=email, password=hashed_pwd, isAdmin=True, company_id=company.id, designation=designation) db.session.add(new_user) db.session.commit() return json.dumps({'status': 1})
def get_all_adOffs(self, request): user, ts = User.get_by_auth_token(int(request.user_id), request.user_token) if user is None: raise endpoints.ForbiddenException('User auth failed') cursor = None if request.last_cursor: cursor = ndb.Cursor.from_websafe_string(request.last_cursor) school_type = None if request.school_type and request.school_type != '': school_type = request.school_type college_rank = None if request.college_rank and request.college_rank != '': college_rank = request.college_rank if school_type and college_rank: ad_off_query = AdmissionsOfficer.query(AdmissionsOfficer.college_rank == college_rank, AdmissionsOfficer.school_type == school_type).order(-AdmissionsOfficer.created, AdmissionsOfficer.key) elif school_type and not college_rank: ad_off_query = AdmissionsOfficer.query(AdmissionsOfficer.school_type == school_type).order(-AdmissionsOfficer.created, AdmissionsOfficer.key) elif not school_type and college_rank: ad_off_query = AdmissionsOfficer.query(AdmissionsOfficer.college_rank == college_rank).order(-AdmissionsOfficer.created, AdmissionsOfficer.key) else: ad_off_query = AdmissionsOfficer.query().order(-AdmissionsOfficer.created, AdmissionsOfficer.key) ad_offs, next_cursor, more = ad_off_query.fetch_page(10, start_cursor=cursor) ret_ad_off = AdmissionsOfficer.ToMessageCollection(ad_offs, next_cursor=next_cursor) return ret_ad_off
def create_user(data): try: new_user = User(username=data['username']) new_user.set_password(data['password']) except KeyError as error: return {'error': 'KeyError: %s' % error} default_tees = data.get('default_tees') if default_tees in TEES: new_user.default_tees = default_tees try: db.session.add(new_user) db.session.commit() return {'success': True} except IntegrityError: db.session.rollback() return {'error': 'IntegrityError: username already exists'}
def post(self): self.response.headers['Content-Type'] = "application/json" jsn = json.loads(self.request.body) token = jsn['token'] user_id = jsn['user_id'] # Reset current user's device token user = User.get_by_auth_token(int(user_id), token) user = user[0] user.deviceToken = None user.put() self.user_model.delete_auth_token(user_id, token) self.send_response(self.RESPONSE_CODE_200, "User logged out", "")
def check_login(self, *args, **kwargs): self.response.headers['Content-Type'] = "application/json" user_id = self.request.get('user_id') token = self.request.get('token') # Does the user id and token exist in the datastore response_tuple = User.get_by_auth_token(int(user_id), token) # Response is a None tuple then the user id & token do not exist if response_tuple == (None, None): self.send_response(self.RESPONSE_CODE_401, "User not authenticated", "") else: return handler(self, *args, **kwargs)
def post(self): #self.response.headers['Access-Control-Allow-Origin'] = 'https://sandboxx.herokuapp.com' # TODO: Change in basehandlers.py #self.response.headers['Access-Control-Allow-Origin'] = 'http://localhost:9000' self.response.headers['Content-Type'] = "application/json" jsn = json.loads(self.request.body) email = jsn['email'] password = jsn['password'] # Login with email and password try: u = self.auth.get_user_by_password(email, password, remember=True, save_session=True) query = User.query(User.email == email) users = query.fetch() user = users[0] ''' # Create Stripe customerID if one doesn't exist if not user.stripeCustomerId: stripe.api_key = stripe.api_key stripe_customer = stripe.Customer.create() stripe_customer_id = stripe_customer.id user.stripeCustomerId = stripe_customer_id user.put() ''' # Merge both objects: auth user object and custom user model user_dict = user.to_dict() del user_dict['created'] results = dict(u.items() + user_dict.items()) results['email'] = email print(results) self.send_response(self.RESPONSE_CODE_200, "", results) except (InvalidAuthIdError, InvalidPasswordError) as e: error_message = 'Login failed for user %s' % email self.send_response(self.RESPONSE_CODE_400, error_message, "")
def test_models(self): u = User.query(User.email == '*****@*****.**').get() self.assertEquals(u.password, u'%s%s' % (u.salt, md5(u'secret').hexdigest())) self.assertTrue(u.check_password(u'secret'))
def auth_user(self, request): try: user = User.get_by_auth_password(request.email, request.password) except (InvalidPasswordError, InvalidAuthIdError): raise endpoints.ForbiddenException('NAW GET OUT') token, ts = User.create_auth_token(user.key.id())
def post(self): self.response.headers['Content-Type'] = "application/json" # Does e-mail already exist? jsn = json.loads(self.request.body) email = jsn['email'] password = jsn['password'] first_name = jsn['first_name'] last_name = jsn['last_name'] phone = jsn['phone'] query = User.query(User.email == email) users = query.fetch() if users: msg = 'Unable to create user. Duplicate email: %s' % email self.send_response(self.RESPONSE_CODE_400, msg, "") return # Create Stripe customer stripe.api_key = utils.get_stripe_api_key() stripe_customer = stripe.Customer.create() stripe_customer_id = stripe_customer.id # If stripe customer Id doesn't exist, set to None if not stripe_customer_id: stripe_customer_id = None # Create a user unique_properties = ['email'] user_data = self.user_model.create_user(email, unique_properties, email=email, password_raw=password, first_name=first_name, last_name=last_name, phone=phone) #stripeCustomerId=stripe_customer_id # If user was not created, probably a duplicate email if not user_data[0]: # user_data is a tuple msg = 'Unable to create user. Duplicate email: %s' % email self.send_response(self.RESPONSE_CODE_400, msg, "") return # New user created. Get user at index 1 user = user_data[1] user_dict = user.to_dict() user_id = user.get_id() token = UserToken.create(user_id, subject='auth', token=None) user_dict['token'] = str(token.token) user_dict['email'] = email del user_dict['created'] del user_dict['updated'] print user_dict self.send_response(self.RESPONSE_CODE_200, "User Signed Up", user_dict)