def signup_user(): if request.json['full_name'] == "" or request.json['username'] == "" or request.json['email'] == "" or request.json['country'] == "" or request.json['password'] == "": return Response(response=str({"message": 'Please, fill all the fields.'}), status=401) new_user = User( full_name=request.json['full_name'], country=request.json['country'], username=request.json['username'], email=request.json['email'], skills=[], password=request.json['password'] ) user = get_user_by_email(new_user.email) # checking if user already exist if user: return Response(response=str({"message": 'email already exist.'}), status=401) # encrypting password salt = bcrypt.gensalt() hashed = bcrypt.hashpw( new_user.password.encode('utf8'), salt).decode('utf8') new_user.password = str(hashed) new_user.save() token = jwt.encode({"_id": str(new_user.id)}, secret_key) res = Response(str(new_user.id)) res.headers['token'] = token return res
def auth_register(): """ Creates a new user in the app Returns: Tuple containing the dict of the new user and status code """ user_fields = user_register_schema.load(request.json) # Check uniqueness of email and return abort instead of getting errors if User.query.filter_by(email=user_fields["email"]).first(): return abort(400, description="Email already registered.") user = User() user.email = user_fields["email"] user.password = bcrypt.generate_password_hash(user_fields["password"]).decode("utf-8") db.session.add(user) db.session.commit() # Need to retrieve the user after adding to the database so that the href and uri fields # can be updated with the correct user id users = User.query.filter_by(email=user_fields["email"]) # Need to remove password from user_fields otherwise it will replace the password hash with # the clear text password entered by the user to register del user_fields["password"] user_fields["href"] = f"https://api.spotify.com/user/{users[0].id}" user_fields["uri"] = f"spotify:user:{users[0].id}" users.update(user_fields) db.session.commit() return (jsonify(user_schema.dump(user)), 201)
def auth_register(): """ Creates a new user in the app Returns: Tuple containing the dict of the new user and status code """ user_fields = user_schema.load(request.json) # Check uniqueness of username/email and return aborts instead of getting errors if User.query.filter_by(username=user_fields["username"]).first(): return abort(400, description="Username is unavailable.") if User.query.filter_by(email=user_fields["email"]).first(): return abort(400, description="Email already registered.") user = User() user.username = user_fields["username"] user.email = user_fields["email"] user.password = bcrypt.generate_password_hash( user_fields["password"]).decode("utf-8") db.session.add(user) db.session.commit() return (jsonify(user_schema.dump(user)), 201)
def register_user(): email = request.form['email'] password = request.form['password'] firstname = request.form['firstname'] lastname = request.form['lastname'] username = request.form['username'] User.register(email=email, password=password, firstname=firstname, lastname=lastname, username=username) return render_template("profile.html", email=session['email'])
def login_user(): email = request.form['email'] password = request.form['password'] if User.login_valid(email, password): User.login(email) return render_template("profile.html", email=session['email']) else: session['email'] = None return render_template('login.html')
def store(): request_data = request.get_json() schema = { 'email': {'type': 'string'}, 'password': {'type': 'string'}, 'name': {'type': 'string'}, 'access': {'required': False, 'type': 'dict', 'schema': { 'admin': {'type': 'boolean'}, 'nde': {'type': 'boolean'}, 'coordenador': {'type': 'boolean'}, 'qualidade': {'type': 'boolean'} }} } v = Validator(schema) if not v.validate(request_data): return jsonify( erro="dados invalidos", message=v.errors ), 400 if request_data.get('access') is None: user = User() user.email = request_data.get('email') user.password = request_data.get('password') user.name = request_data.get('name') else: user = User.from_json(json.dumps(request_data)) user.save() return jsonify(user.to_dict()), 200
def signUpUser(): username = request.form['username'] email = request.form['email'] password = request.form['password'] user = User(username, email, password) user.save_to_mongo() session['email'] = email flash("You were Successfully Registered!") return redirect(url_for('display_dashboard'))
def seed_db(): from src.models.User import User from src import bcrypt from faker import Faker import random faker = Faker() users = [] TEST_PASSWORD = current_app.config["TEST_PASSWORD"] if not TEST_PASSWORD: raise ValueError('TEST_PASSWORD not provided.') for i in range(5): # Add users user = User() user.email = f"test{i}@test.com" user.bio = faker.paragraph(nb_sentences=3) user.username = f"test{i}" user.first_name = faker.first_name() user.last_name = faker.last_name() user.password = bcrypt.generate_password_hash( f"{TEST_PASSWORD}").decode("utf-8") db.session.add(user) db.session.commit() print("Users Added") print("Tables seeded")
def read_users_from_json(self, users_json): self.users.clear() for u in users_json: created_user = User(u['id'], u['suspicious'], u['permissions']) for c in u['user_components']: # if len(c['vendor']) > 0 and len(c['product']) > 0: # if legal vendor_name and product_name found_component = next( ( x for x in self.components if # search if component already exists x.id == c['id']), None) if found_component is not None: created_user.add_component(found_component, c['update']) self.users.append(created_user)
def update_user(user: User, my_db: MyDBConnection, firstname: str = None, surname: str = None, login: str = None, pwd: str = None, poster: str = None, list_preferences: List[Show] = None): user.update_user_in_bdd(my_db=my_db, firstname=firstname, surname=surname, login=login, pwd=pwd, poster=poster, list_preferences=list_preferences)
def add_user(firstname: str, surname: str, login: str, pwd: str, poster: str, my_db: MyDBConnection, list_preferences: List[Show] = None): user = User.retrieve_user_from_credentials(login, pwd, my_db) if user is None: user = User(firstname, surname, login, pwd, poster, list_preferences) user.create_user_in_bdd(my_db) return user else: raise ErrorUserAlreadyExist
def admin_login(): """ Login a user :return: """ # Pass the post details post = Utils.parse_json(request) # Check if email and password in the post if 'email' not in post or 'password' not in post: return Respond.error("Email password not found", error_code=422) # Find the user with that email user = User.query(User.email == post['email']).get() # If user not found if user is None: return Respond.error("User not found with the provided email", error_code=404) if user.type != "Admin" and user.type != "Creator": return Respond.error("Login with password not allowed", error_code=422) # If password not correct if not user.verify_password(post['password']): return Respond.error("Password incorrect") # Make token token = user.make_token() # Respond with user and token return Respond.success({"token": token, "user": user.as_dict()})
def get_user(): token = request.headers.get('Authorization') user = User.from_token(token) if user is None: return False else: return user
def register_user(**kwargs): error_message = validate_user_input(kwargs) if error_message : # return Response({'error_msg':error_message}, status = 400) return {'error_msg':error_message}, 400 else: user_record= User.query.filter(User.user_name == kwargs.get("user_name")).first() if user_record: #return Response({'error_msg':"User Name already exists"}, status = 400) return {'error_msg':"User Name already exists"}, 400 password_salt = generate_salt() password_hash = generate_hash(kwargs.get("password"), password_salt) new_user = User(user_name=kwargs.get("user_name"), shop_name=kwargs.get("shop_name"), drug_licence_1=kwargs.get("drug_license_1"), drug_licence_2=kwargs.get("drug_license_2"), gstr_number=kwargs.get("gst_number"), aadhar_pan_number=kwargs.get("aadhar_pan"), phone_number=kwargs.get("phone"), shop_address= kwargs.get("address_shop"), password_hash=password_hash, password_salt=password_salt) db.session.add(new_user) # Adds new User record to kwargs.getbase db.session.commit() # Commits all changes return None, 201
def activate_pro(user): """ Activate pro usage for the user :param user: :return: Response """ # Perform checks if user.getPoints() < PRO_COST: return Respond.error('Low balance', error_code=420) if user.pro: return Respond.error('User already a pro', error_code=410) post = Utils.parse_json(request) users_with_device = User.query(User.device == post['device']).fetch() if len(users_with_device) > 0: return Respond.error('Device already registered by another user') # Activate Pro for user on this device user.subtractPoints(PRO_COST, 'Activated Pro') user.pro = True user.device = post['device'] user.put() return Respond.success('Activated pro for user')
def auth_register(): user_fields = user_schema.load(request.json) user = User.query.filter_by(email=user_fields["email"]).first() if user: return abort(400, description="User already") user = User() user.email = user_fields["email"] user.password = bcrypt.generate_password_hash( user_fields["password"]).decode("utf-8") db.session.add(user) db.session.commit() return jsonify(user_schema.dump(user))
def signup(): """ GET returns the template for the signup page, when the form is submitted the data is sent back to the endpoint using POST which creates a new user. """ form = SignUpForm() if form.validate_on_submit(): if not User.check_unique_username(form.username.data): flash("A user already exists with that username.") elif not User.check_unique_email(form.email.data): flash("A user already exists with that email address.") else: user = User() user.username = form.username.data user.email = form.email.data user.password = bcrypt.generate_password_hash( form.password.data).decode("utf-8") db.session.add(user) db.session.commit() login_user(user) return redirect(url_for("users.dashboard")) return render_template("signup.html", form=form)
def edit_user_account_details(): """ GET returns the template for the edit account page, when the form is submitted the data is sent back to the endpoint using POST which updates the users account data. """ form = EditUserAccountForm() if form.validate_on_submit(): if current_user.username != form.username.data and not User.check_unique_username( form.username.data): flash("A user already exists with that username.") elif current_user.email != form.email.data and not User.check_unique_email( form.email.data): flash("A user already exists with that email address.") elif form.new_password.data and not current_user.check_password( form.current_password.data): flash("Your current password is incorrect.") else: user = User.query.filter_by(id=current_user.id) data = {} if form.username.data: data["username"] = form.username.data if form.email.data: data["email"] = form.email.data if form.confirm_password.data: data["password"] = bcrypt.generate_password_hash( form.confirm_password.data).decode("utf-8") fields = user_schema.load(data, partial=True) user.update(fields) db.session.commit() flash("Account details updated successfully.") return redirect(url_for("users.get_user_account_details")) # Prepopulate the form with existing data form.username.data = current_user.username form.email.data = current_user.email return render_template("account_edit.html", form=form)
def update_user_vouch(target_id: int, positive: bool, session): ''' Get user first from database, then update vouch number ''' user_obj = User.get_user(target_id, session) if positive: user_obj.vouches += 1 else: user_obj.vouches -= 1 user_obj.update(user_obj.vouches, session)
def destroy(): try: user = User.objects(id=id).get() return jsonify(), 200 except (User.DoesNotExist, ValidationError): output = {"error": {"msg": "500 error: User not found."} } resp = jsonify({'result': output}) resp.status_code = 500 return resp
def logoutAll(self): """ method to set all users offline prevent any bug and crash some user's login """ users = self.userRepository.fetchLogged() if users != 'no online users': for user in users: user['isLogged'] == False usr = User(user['username'], user['password']) self.userRepository.update(usr)
def login_user(): email = request.form['email'] password = request.form['password'] validate = User.is_login_valid(email, password) if validate is True: session['email'] = email return redirect(url_for('display_dashboard')) else: flash("Put in the correct email and password") return render_template("login.html")
def wrapper_func(*args, **kwargs): token = request.headers.get('Authorization') if token is None: return Respond.error('Auth Required', 401) user = User.from_token(token) if user is None: return Respond.error('User not found', 400) else: return original_function(user, *args, **kwargs)
def wrapper_func(*args, **kwargs): token = request.headers.get('Authorization') if token is None: return Respond.error('Auth Required', 401) user = User.from_token(token) if user is None: return Respond.error('User not found', 400) elif (user.type != 'Admin' and user.type != 'Creator'): return Respond.error("Permission Denied", 422) else: return original_function(user, *args, **kwargs)
def user_register(): if current_user.is_authenticated: return redirect(url_for('user.user_home')) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() flash('Your account has been created! You are now able to log in', 'success') return redirect(url_for('user.user_login')) return render_template('register.html', title='Register', form=form)
def create(cls, **kwargs) -> User: user = User(**kwargs) db.session.add(user) db.session.commit() current_app.logger.info("Created user '{0}'.".format(user.username)) # Setting default role for this user default_role = RoleService.default_role() if default_role: cls.add_role(user.username, role_name=default_role.name) return user
def seed_db(): from src.models.User import User from src.models.Profile import Profile from faker import Faker from src import bcrypt import random from random import seed from random import randint faker = Faker() profiles = [] for i in range(10): user = User() user.email = f"test{i}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") db.session.add(user) db.session.commit() for i in range(10): profile = Profile() profile.username = faker.name() profile.fname = faker.first_name() profile.lname = faker.last_name() profile.account_active=faker.boolean() profile.employer=faker.boolean() profile.contractor=faker.boolean() profile.user_id = i+1 profiles.append(profile) db.session.add(profile) db.session.commit() print("Tables seeded")
def social_login(): """ Login via google With the id token get user details, if the user does not exist then create it. If the user is coming back then just save the id token Then make a token and send it to the client """ post = Utils.parse_json(request) id_token = post['id_token'] url = 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=%s' % id_token try: result = urlfetch.fetch(url) if result.status_code == 200: result = json.loads(result.content) name = result['name'] email = result['email'] picture = result['picture'] else: error = 'Status code: {} , Response: {}'.format( result.status_code, result.content) logging.error(error) return Respond.error('Error getting user info from google.') except urlfetch.Error: logging.exception('Caught exception fetching url') return Respond.error('Error getting user info from google.') users = User.query(User.email == email).fetch() if len(users) > 1: return Respond.error("There was an error", error_code=422) elif len(users) == 1: # User already exists. Just make a token and return user = users[0] # Make token token = user.make_token() # Respond with user and token return Respond.success({"token": token, "user": user.as_dict()}) else: # New User. Create and send token user = User(name=name, email=email, picture_uri=picture) user.put() # Make token token = user.make_token() # Respond with user and token return Respond.success({"token": token, "user": user.as_dict()})
def register_user_svc(**kwargs): """ Register new user service :param kwargs: :return: user query object """ user = get_user_by_email(kwargs["email"]) if user: return None user = User() user.email = kwargs["email"] user.username = kwargs["username"] user.f_name = kwargs["f_name"] user.l_name = kwargs["l_name"] user.bio = kwargs["bio"] user.password = bcrypt.generate_password_hash(kwargs["password"]).decode("utf-8") db.session.add(user) db.session.commit() return user
def update(): request_data = request.get_json() schema = { 'email': {'type': 'string'}, 'password': {'type': 'string'} } v = Validator(schema) if not v.validate(request_data): return jsonify(erro="dados invalidos"), 400 try: user = User.objects(id=get_jwt_identity()).get() print(user.email) user.email = request_data.get('email') user.password = request_data.get('password') user.save() return jsonify(user) except: return forbidden()
def login(self, username, password): self.logger.debug("login") wrong_credential = False if username != "" and password != "": if self.loginController.login(username, password): hash_password = pwhash.scrypt.str(password.encode('utf8')) self.user = User(username, hash_password) self.create_home(username) else: wrong_credential = True else: wrong_credential = True self.notify(connected=self.connected, wrong_credential=wrong_credential, username=username)
def update_user(): try: userData = json.loads(request.data) print(userData) except Exception as e: responseData.code = 500 responseData.data = repr(e) responseData.message = "操作失败" return jsonify(responseData.to_json()) # 请求数据正常 u = User(id=userData.get('id'), name=userData.get('name')) responseData.data = userService.update_user(u) if responseData.data > 0: responseData.code = 200 responseData.data = u.id responseData.message = "操作成功" else: responseData.code = 500 responseData.data = "服务器更新数据失败" responseData.message = "操作失败" return jsonify(responseData.to_json())