def put_user(id, jsonn): user = User.query.filter(User.id == id).first() if not user: return False if jsonn['name']: user.name = jsonn['name'] if jsonn['cpf']: if User.query.filter(User.cpf == jsonn['cpf']).first(): return False user.cpf = jsonn['cpf'] if jsonn['email']: user.email = jsonn['email'] if jsonn['password']: if jsonn[ 'password_old'] and user.password_hash == User.set_password( jsonn['password_old']): user.password_hash = User.set_password(jsonn['password']) else: return False db.session.add(user) db.session.commit() user_schema = UserSchema() return user_schema.dump(user)
def add_user(): if request.method == 'POST': data = request.get_json() user = User(data['email'], data['firstname'], data['lastname'], data['password']) users.append(user) return jsonify(user.create_user()), 201
def post(cls): '''post (signup method)''' data = request.get_json() result = validate.check_for_data(data) if result: return result, 400 username = data.get("username") name = data.get("name") email = data.get("email") password = data.get("password") confirm_password = data.get("confirm_password") message = "" if not confirm_password: message = "Please Re-enter password" if not password: message = "Please enter password" if not email: message = "Please enter email" if not username: message = "Please enter username" if not name: message = "Please enter name" if message: return dict(message=message), 400 passwords = [password, confirm_password] result = validate.validate_register(username, name, email, passwords) if "message" in result: return result, 400 my_user = User() result = my_user.add_user(name, username, email, password) if "error" in result: return dict(message=result["message"]), result["error"] return result, 201
def create_user(): # """Endpoint to create a user.""" new_user = User(user_name='user1') db.session.add(new_user) db.session.commit() return jsonify(network=new_user.to_dict())
def mutate(self, info, username, password, email): user = User.query.filter_by(username=username).first() if user: return CreateUser(user=user) user = User(username=username, password=password, email=email) if user: User.save(user) return CreateUser(user=user)
def add_new_user(): name = request.form.get('name') username = request.form.get('username') password = request.form.get('password_hash') role = request.form.get('role') new_user = User(name=name, username=username, role_id=role) new_user.set_password(password) db.session.add(new_user) db.session.commit() logger.info( f"admin:{session['admin_logged'].get('username')} - added new user {username}" ) return redirect('/admin/user')
def update_user(self, user_id=None, data=None): """Updates the User on the service. Arguments: user_id {string} -- the id of user to update (required) data {dict} -- the new update data for the user Returns: object -- the added user object or None """ if user_id is None: raise ValueError('user id to update cannot be None') if data is None: raise ValueError('user data cannot be None or empty') data['last_modified_at'] = datetime.datetime.now() try: updated_rows = User.update(**data).where(User.user_id == user_id).execute() return updated_rows > 0 except Exception as err: self.logger.error('Error Occurred: {error}'.format(error=err)) raise LookupError('Update Error: User does not exists on this service') return False
def post(cls): '''post (login) method''' data = request.get_json() result = validate.check_for_data(data) if result: return result, 400 username = data.get("username") password = data.get("password") if not username or not password: return dict(message="Username or password fields missing"), 400 my_user = User() result = my_user.login(username, password) if "error" in result: return dict(message=result["message"]), result["error"] access_token = create_access_token(identity=username) return dict(result, token=access_token), 200
def login(self, username=None, password=True): """Checks whether the user with the username and password can log into the application. Arguments: username {string} -- Username of user password {string} -- Password of user Returns: object -- the user object or None """ if username is None: raise ValueError('the username cannot be None') if password is None: raise ValueError('the password cannot be None') # Todo: finish up the login try: user = User.select().where(User.username == str(username)).get() return Utilities.convert_unserializable_fields(model_to_dict(user)) except Exception as err: self.logger.error('Error Occurred: {error}'.format(error=err)) raise LookupError('User does not exists on this service') return None
def add_user(self, data=None, user_id=None): """Adds a new User on the service. Arguments: data {dict} -- the data for the new user user_id {string} -- the id of user to add if available Returns: object -- the added user object or None """ if data is None: raise ValueError('user data cannot be None or empty') if user_id is None: user_id = Utilities.generate_id() # generate an uuid for this record data['user_id'] = user_id # set the user_id for this record try: saved_user = User.create(**data) return model_to_dict(saved_user) except Exception as err: self.logger.error('Error Occurred: {error}'.format(error=err)) raise ValueError('Unable to save the user object') return None
def register(): if current_user.is_authenticated: return jsonify({"Error": 'already loggedIn'}), 404 if User.query.filter_by(email=request.json['email']).first() is not None: return jsonify({"Error": 'email already exists'}), 409 if User.query.filter_by( username=request.json['username']).first() is not None: return jsonify({"Error": 'username already exists'}), 409 if request.json['password'] != request.json['confirm_password']: return jsonify({"Error": 'password doesnt match'}) hashed_password = bcrypt.generate_password_hash( request.json['password']).decode('utf-8') new_user = User(username=request.json['username'], email=request.json['email'], password=hashed_password) db.session.add(new_user) db.session.commit() login_user(new_user) resp = sendmail(current_user.id, request.json['email']) return jsonify(current_user.id), 201
def admin_create_user(): from app.app import db form = UserForm() if form.validate_on_submit(): password = os.urandom(24) exist = db.session.query(User).filter_by(email=form.email.data).first() if exist is not None: return render_template( 'admin/create_user.html', form=form, error='There is already an account with this email address') new_user = User(username=form.username.data, email=form.email.data, password=password, active=True) for role in form.my_roles.data: if role == 'user': new_user.roles.append(fetch_user_role()) elif role == 'admin': new_user.roles.append(fetch_admin_role()) db.session.add(new_user) email = form.email.data # We ill send an email to the user asking him to reset his password token = generate_confirmation_token(email) confirm_url = url_for('routes.reset_password', token=token, _external=True) html = render_template('mail_reset_password.html', confirm_url=confirm_url) subject = "Leosac select password" send_email(email, subject, html) db.session.commit() return redirect(url_for('routes.dashboard')) return render_template('admin/create_user.html', form=form)
def register(): from app.app import db """Register Form""" form = MyRegisterForm() if form.validate_on_submit(): exist = db.session.query(User).filter_by(email=form.email.data).first() if exist is not None: return render_template( 'register.html', form=form, error='There is already an account with this email address') new_user = User(username=form.username.data, email=form.email.data, password=form.password.data, active=True, confirmed=False) new_user.roles.append(fetch_user_role()) token = generate_confirmation_token(new_user.email) confirm_url = url_for('routes.confirm_email', token=token, _external=True) html = render_template('mail_confirmation_account.html', confirm_url=confirm_url) subject = "Please confirm your email" send_email(new_user.email, subject, html) flash('A confirmation email has been sent via email.', 'success') db.session.add(new_user) db.session.commit() return redirect(url_for('routes.login')) return render_template('register.html', form=form)
def register(): if request.method == 'POST': new_user = User(username=request.form['username'], password=request.form['password']) db.session.add(new_user) db.session.commit() return render_template('login.html') return render_template('register.html')
def create(): newUser = User(email=request.json.get("email", None), mobile=request.json.get("mobile", None), user_name=request.json.get("user_name", None), country=request.json.get("country", None), password=request.json.get("password", None)) API.save_changes(newUser) return jsonify(status='saved', ), 200
def delete(self, user_email=None): if user_email: user = User.objects(user_email=user_email) if user: user.delete() return "Success", 200 return "Invalid user_email", 404 return "Method not allowed", 405
def get(self, user_email=None): if not user_email: return User.objects.to_json() else: user = User.objects(user_email=user_email) if user: return user.to_json() return "Record Not found", 404
def user_register(): data = request.get_json() errors = register_schema.validate(data) if errors: return utils.response_bad_request(errors) if user_service.get_user_by_email(data.get('email','').lower()): return utils.response_bad_request('E-mail já possui cadastro.') user = User(**data) user.email = user.email.lower() user,error = user_service.save_user(user) if error: return utils.response_server_error(error) return utils.response_created('Usuário criado com sucesso.')
def test_create_user(mock_update_db): # make sure there are no errors creating a user user = User( username="******", password="******", ) assert type(user) == User
def register(): # 首先创建一个空白的注册表单 form = RegisterForm(request.form) # 当客户端浏览器请求此URL时的方法是GET,这时候将包含表单的html文件返回 if request.method == 'GET': return render_template('web/register.html', form=form) else: # 当用户填写好表单,点击"注册"按钮后,此时的方法是POST,这时应该获取表单内容 new_user = User() new_user.username = form.username.data new_user.password = form.password.data # 然后判断信息合法性并提交数据库 if User.query.filter_by(username=new_user.username).first(): flash('用户名已存在,请更换') # 通过flask自带的flash给出一个警告,在html中编写相应的script实现 return redirect(url_for('web.register')) else: with db.auto_commit(): db.session.add(new_user) return redirect(url_for('web.login'))
def registration(): name = request.json['u_name'] username = request.json['username'] password = request.json['password'] user = check_user_registration(username) if user: return error_response(400, 'User has already registered') new_user = User(name=name, username=username) new_user.set_password(password) login_user(new_user) db.session.add(new_user) db.session.commit() logger.info(f'user:{username} - has been registred') return jsonify({'Success': 'User has been registered'})
def saveAsset(self, emailAddress): existing_assets = self.findAssets(emailAddress) if not existing_assets: asset = { "userID": User.findUser(emailAddress)["_id"], "symbol": self.symbol, "amount": self.amount, "avarage_price": self.avarage_price } else: update_amount = int(existing_assets['amount']) + int(self.amount) find_col = { "name": "userID", "value": User.findUser(emailAddress)["_id"] } set_col = {"name": "amount", "value": update_amount} return print(Database_manager().update_one(find_col, set_col, self.collection)) Database_manager().save_one(asset, self.collection)
def test_hash_password(): salt = bytearray("salt", "ascii") password = "******" hash = User.hash_password(password, salt) assert ( hash == b"^^+w\x02\xa7\xcb!\xa0x2\xab\xe4K\xda\n\x97\xde\xf6\xfd\xc1\xd0\xc3?\xe8\xeb\xac\xd4l\x8d\xdc\xb3" # noqa: E501 )
def register(): try: list_role = ["ADMIN", "HOTEL_OWNER", "USER"] username = request.get_json()['username'] password = bcrypt.generate_password_hash( request.get_json()['password']).decode('utf-8') role = request.get_json()['role'] if role not in list_role: return custom_response({"error": "Invalid role"}, 400) newuser = User(username, password, role) user = User.get_user_by_username(username) if (user != None): return custom_response({"error": "Duplicate username"}, 400) else: db.session.add(newuser) db.session.commit() result = newuser.dump() return custom_response(result, 200) except Exception as e: return custom_response({"error": str(e)}, 400)
def after_login(resp): if resp.email is None or resp.email == '': flash('Invalide login. Please try again.') redirect(url_for('login')) user = User.query.filter_by(email=resp.email).first() if user is None: nickname = resp.nickname if nickname is None or nickname == '': nickname = resp.email.split('@')[0] user = User(nickname=nickname, email=resp.email) db.session.add(user) db.session.commit() db.session.add(user.follow(user)) db.session.commit() remember_me = False if 'remember_me' in session: remember_me = session['remember_me'] session.pop('remember_me', None) login_user_local(user, remember=remember_me) return redirect(request.args.get('next') or url_for('index'))
def register(): form = RegisterForm() if form.validate_on_submit(): user = User(nickname=form.nickname.data, email=form.email.data, password=form.password.data, about_me=form.about_me.data) db.session.add(user) db.session.commit() flash('Your changes have been saved.') return redirect(url_for('login')) return render_template('pages/user/register.html', form=form)
def put(self, user_email=None): data = json.loads(request.data) if user_email: user = User.objects(user_email=user_email) if user: if 'user_email' in data.keys(): del data['user_email'] if user.update(**data): return "Success", 200 return "Failed to update", 500 return "Invalid user_email", 404 return "Method not allowed", 405
def login(): if ("username" in session): flash("You already logged in", "error") return render_template("welcomescreen.html", user=session['username']) if request.method == "POST": existing_user = User.findUser(request.form.get('email').lower()) if(existing_user): if(PasswordHelper.checkPassword(request.form.get('password'), existing_user['password'])): user = User(existing_user['firstname'], existing_user['emailaddress'], existing_user['password']) flash("Welcome back {}".format(user.firstName), "success") session['username'] = user.firstName session['emailaddress'] = user.emailAdress return render_template('assets.html', user=session['username']) else: flash("Username and/or password are incorrect", "error") else: flash("Username does not exist", "error") return render_template('login.html')
def post(self): data = json.loads(request.data) new_user = User() new_user.username = data['username'] new_user.user_email = data['user_email'] new_user.location = data.get('location') _id = new_user.save() return str(_id.id), 201
def reset(): """ 初始化 :return: """ # 执行sql脚本,数据清空 db.drop_all() db.create_all(app=app) user = User(username='******', password='******') db.session.add(user) db.session.commit() # username = session['username'] # auth_service.reset_password(username) return redirect(url_for("auth.login"))