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(): 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 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 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 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 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 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 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() 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 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"))
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(name=form.name.data, cpf=form.cpf.data, email=form.email.data, 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', title='Register', form=form)
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 save_new_user(data): try: new_user = User(name=data['name'], email=data['email'], photo_url=data['photo_url'], uid=data['uid'], registered_on=datetime.utcnow() + timedelta(hours=9), last_login=datetime.utcnow() + timedelta(hours=9), cnt_login=0) db.session.add(new_user) db.session.commit() except Exception as e: print(e) abort(500) return new_user
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 register(form): current_app.logger.info( "需要注册内容%s", json.dumps(form.data, ensure_ascii=False, indent=4, separators=(',', ':'))) username = form.username.data # 查询用户是否已存在 user_info = User.query.filter(username == username).first() if user_info: current_app.logger.error("用户名已存在:[%s],请重新输入", username) else: str_password = form.password.data user = User(username, str_password) save_user(user)
def create_user(**kwargs): user = User( name=kwargs['name'], description=kwargs['description'], email=kwargs['email'], create_at=kwargs['create_at'], password=kwargs['password'], user_type=kwargs['user_type'] ) try: db.session.add(user) db.session.commit() return build_api_response(HTTPStatus.CREATED) except IntegrityError: return build_api_response(HTTPStatus.BAD_REQUEST)
def create(): data = request.get_json() user = User( name=data["name"], description=data['description'], email=data['email'], password=hashlib.sha256(data['password'].encode('utf-8')).hexdigest(), create_at=datetime.now().astimezone(fuso_horario).strftime( '%d/%m/%Y %H:%M:%S'), ) try: db.session.add(user) db.session.commit() return build_api_response(HTTPStatus.CREATED) except IntegrityError: return build_api_response(HTTPStatus.BAD_REQUEST)
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 load_test_data(): """Load test data into db.""" courses = [ course_with_coupons_and_quotes, course_without_coupons_and_quotes ] users = [admin_user] review_quotes = ["Wowza", "Stinks"] try: for course in courses: Course(**course) for user in users: User(**user) course = Course.query.first() for review_quote in review_quotes: ReviewQuote(body=review_quote, courseId=course.id) for coupon in coupons: Coupon(**coupon, courseId=course.id) for talk in talks: Talk(**talk) for tag in tags: Tag(tagName=tag) for cheat_sheet in cheat_sheets: CheatSheet(**cheat_sheet) # artifically backdate the regex cheat sheet to test updating the date cheat_sheet = CheatSheet.query.filter( CheatSheet.title == "Regex Cheat Sheet", ).one() cheat_sheet.updated_at = date(2020, 2, 2) db.session.add(cheat_sheet) db.session.commit() except (IntegrityError, UniqueViolation, SQLAlchemyError, InvalidRequestError) as e: # Keep from printing hundreds of lines simply for a db issue red = "\033[91m" print(f"{red}>>>>>>>>CORRUPT DATABASE<<<<<<<<<") print(f"{red}{e}")
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 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 load_test_data(): """Load test data into db.""" courses = [ course_with_coupons_and_quotes, course_without_coupons_and_quotes ] users = [admin_user] review_quotes = ["Wowza", "Stinks"] for course in courses: Course(**course) for user in users: User(**user) course = Course.query.first() for review_quote in review_quotes: ReviewQuote(body=review_quote, courseId=course.id) for talk in talks: Talk(**talk)
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 create_user(post_data): # check if user already exists user = User.query.filter_by(user_id=post_data.get('id')).first() if not user: user = User( user_id=post_data.get('id'), first_name=post_data.get('first_name'), last_name=post_data.get('last_name'), username=post_data.get('username'), photo_url=post_data.get('photo_url') ) # insert the user db.session.add(user) db.session.commit() return {"data": { "user": { "user_id": user.user_id, "first_name": user.first_name, "last_name": user.last_name, "username": user.username, "photo_url": user.photo_url }, "status": 201, "error": None }} else: return {"data": { "user": { "user_id": user.user_id, "first_name": user.first_name, "last_name": user.last_name, "username": user.username, "photo_url": user.photo_url }, "status": 200, "error": f"User {user.username} already exists." }}
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") if not username or not name or not email or not password or not confirm_password: return dict( message="name, username, email, password or confirm_password fields missing"), 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