def register_user(): # get post data post_data = request.get_json() if not post_data: response_object = {'status': 'error', 'message': 'Invalid payload.'} return jsonify(response_object), 400 email = post_data.get('email') password = post_data.get('password') try: # check for existing user user = User.query.filter(or_(User.email == email)).first() if not user: # add new user to db new_user = User(email=email, password=password) db.session.add(new_user) db.session.commit() # generate auth token auth_token = new_user.encode_auth_token(new_user.id) response_object = { 'status': 'success', 'message': 'Successfully registered.', 'auth_token': auth_token.decode() } return jsonify(response_object), 201 else: response_object = { 'status': 'error', 'message': 'Sorry. That user already exists.' } return jsonify(response_object), 400 # handler errors except (exc.IntegrityError, ValueError) as e: db.session().rollback() response_object = {'status': 'error', 'message': 'Invalid payload.'} return jsonify(response_object), 400
def users(): user1 = User('stacon', 'secret', 100) user2 = User('filgeo', 'secret', 100) user3 = User('lirnik', 'secret', 85) user4 = User('tasmas', 'secret', 1) user5 = User('liknik', 'secret', 1) user6 = User('biktik', 'secret', 1) user7 = User('sikpap', 'secret', 1) user8 = User('paptap', 'secret', 1) user9 = User('lamtam', 'secret', 1) user10 = User('aimfak', 'secret', 1) try: db.session.add(user1) db.session.add(user2) db.session.add(user3) db.session.add(user4) db.session.add(user5) db.session.add(user6) db.session.add(user7) db.session.add(user8) db.session.add(user9) db.session.add(user10) db.session.commit() except exc.IntegrityError: flash('Failed to seed Users in database, they probably already exist', 'error') return redirect(url_for('seeders.index')) flash('Users seeded', 'success') return redirect(url_for('seeders.index')) return redirect(url_for('seeders.index'))
def test_user_model(self): user1 = User("testuser", "testuserlast", "*****@*****.**", "testuserpass", "customer") user2 = User("testuser2", "testuser2", "*****@*****.**", "shop1pass", "customer", 1, "8506667676") db.session.add(user1) db.session.add(user2) db.session.commit() self.assertEqual(User.query.count(), 2)
def test_employee_model(self): user1 = User("testuser", "testuserlast", "*****@*****.**", "testuserpass", "customer") user2 = User("testuser2", "testuser2last", "*****@*****.**", "shop1pass", "employee", 1, "8506667676") db.session.add(user1) db.session.add(user2) db.session.commit() empl_count = User.query.filter_by(role="employee").count() self.assertEqual(empl_count, 1)
def register_shop_employee(self): user1 = User("shop1", "shop1", "*****@*****.**", "shop1pass", "shop", 1, "8506667676") new_shop = Shop("shop1", 'location') db.session.add(new_shop) new_shop.users.append(user1) user2 = User("testuser2", "testuser2last", "*****@*****.**", "shop1pass", "employee", 1, "8506667676") new_shop.users.append(user2) db.session.commit() empl = User.query.filter_by(email="*****@*****.**").first() return empl
def test_shop_model(self): user1 = User("testuser", "testuserlast", "*****@*****.**", "testuserpass", "shop") user2 = User("shop1", "shop1", "*****@*****.**", "shop1pass", "shop", 1, "8506667676") new_shop = Shop("shop1", 'location') new_shop.users.append(user2) db.session.add(user1) db.session.add(user2) db.session.commit() u1 = User.query.filter_by(first_name="shop1").first() shop1 = Shop.query.filter_by(shop_name="shop1").first() self.assertEqual(u1.shop_id, shop1.shop_id)
def register(): app.logger.debug("Applying register") form = RegisterForm(request.form) if form.validate_on_submit(): app.logger.debug("It was validated user information for registering") user = User.query.filter_by(email=form.email.data).first() if user: app.logger.debug('This user exists') flash('This user exists','error-message') return render_template(url_for('auth/register.html',form=form)) User.create(**form.data) app.logger.debug("User registered sucessfully") flash("The user was registered successful") return render_template("auth/register.html",form=form)
def register(): # restrict access for non admins if not current_user.is_admin: flash('You need to have admin access level for this page', 'error') return redirect(url_for('main.index')) form = RegistrationForm() if form.validate_on_submit(): new_user = User( username=form.username.data, password=form.password.data, privileges_level=form.privilege_level.data ) # add user to database db.session.add(new_user) db.session.commit() flash(u'User {} created successfully'.format(form.username.data), 'success') # redirect to users panel return redirect(url_for('auth.index')) # load registration template return render_template("auth/register.html", form=form, title='User registration')
def signup(): """ Permite a un usuario registrarse en el sistema Returns: Si no existe un usuario con los datos introducidos en el sistema lo añade al sistema y le redirige a la página de inicio de sesión. Si existe entonces lo redirige a la página de inicio de sesión. """ # If sign in form is submitted form = RegisterForm(request.form) # Verify the sign in form if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: flash('Usuario ya existe', 'error-message') form = LoginForm(request.form) return render_template("auth/signin.html", form=form) else: a = User(form.username.data, form.email.data, form.password.data, 'user', '0') db.session.add(a) db.session.commit() form = LoginForm(request.form) return redirect(url_for('auth.signin')) return render_template("sigup.html", form=form)
def add_manager(): print(check_logged_in(1)) if check_logged_in(1): form = RegisterWorker(request.form) if request.method == 'POST' and form.validate(): username = form.name.data emailID = form.email.data password = form.password.data role = 2 error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif User.query.filter_by(emailID=emailID).first() is not None: error = 'User {} is already registered.'.format(username) if error is None: temp = User(username, emailID, generate_password_hash(password), role) db.session.add(temp) db.session.commit() db.session.add(employeeInfo(temp.id, int(session['user_id']))) db.session.commit() return redirect(url_for('owner.index')) return render_template('owner/add_employee.html', form=form, title="Add Manager Page", role=str(session['role'])) return redirect(url_for('landing.index'))
def signup(): form = SignupForm(request.form) if form.validate_on_submit(): user = User(email=form.email.data, name=form.name.data, password=generate_password_hash(form.password.data)) try: db.session.add(user) db.session.commit() # Since we are redirecting to the signin page # we don't need to save the session. # session['user_id'] = user.id flash('Usuario creado con éxito. :)') return redirect(url_for('auth.signin')) except IntegrityError as ie: db.session.rollback() flash(str(ie)) except Exception as e: db.session.rollback() flash(str(e)) return render_template('auth/signup.html', form=form)
def google_logged_in(blueprint, token): if not token: flash("Failed to log in with Google.", category="error") return False resp = blueprint.session.get("/oauth2/v2/userinfo") if not resp.ok: msg = "Failed to fetch user info from Google." flash(msg, category="error") return False google_info = resp.json() google_user_id = str(google_info["id"]) # Find this OAuth token in the database, or create it query = OAuth.query.filter_by( provider=blueprint.name, provider_user_id=google_user_id, ) try: oauth = query.one() except NoResultFound: oauth = OAuth( provider=blueprint.name, provider_user_id=google_user_id, token=token, ) if oauth.user: login_user(oauth.user) flash("Successfully signed in with Google.") if oauth.user.role == "customer": # check if customer or provider return redirect(url_for('mod_customer.dashboardcustomer')) else: return redirect(url_for('mod_provider.dashboardprovider')) else: #print("in else ", file=sys.stdout) #print(resp.json, file=sys.stdout) # Create a new local user account for this user user = User( # Remember that `email` can be None, if the user declines # to publish their email address on GitHub! email=google_info["email"], first_name=google_info["given_name"], last_name=google_info["family_name"], password="******", role="customer") # Associate the new local user account with the OAuth token oauth.user = user # Save and commit our database models db.session.add_all([user, oauth]) db.session.commit() # Log in the new local user account login_user(user) flash("Successfully signed in with Google.") return redirect(url_for('mod_customer.dashboardcustomer')) # Disable Flask-Dance's default behavior for saving the OAuth token return False
def signup(): # Check if not already signed in if 'user_id' in session: return redirect(url_for('landing.index')) form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): username = form.name.data emailID = form.email.data password = form.password.data role = int(form.role.data) error = None if not username: error = 'Username is required.' elif not password: error = 'Password is required.' elif User.query.filter_by(emailID=emailID).first() is not None: error = 'User {} is already registered.'.format(username) if error is None: db.session.add( User(username, emailID, generate_password_hash(password), role)) db.session.commit() return redirect(url_for('auth.signin')) return render_template('auth/signup.html', form=form, title="Sign Up Page")
def get_employee_list(ownerID, status=''): manager_id_list = employeeInfo.query.filter_by(ownerID=ownerID).all() employee_id_list = manager_id_list unassigned_managers = [] assigned_managers = [] gardeners_list = [] for manager in manager_id_list: if nurseryStaff.query.filter_by(eID=manager.eID).first() is not None: gardeners_list += employeeInfo.query.filter_by( ownerID=manager.eID).all() assigned_managers.append(manager) else: unassigned_managers.append(manager) if status == 'assigned': employee_id_list = assigned_managers + gardeners_list elif status == 'unassigned': employee_id_list = unassigned_managers else: employee_id_list = manager_id_list + gardeners_list employee_details_list = [] for employee_id in employee_id_list: employee_details_list.append( User.get_details(User.query.filter_by(id=employee_id.eID).first())) return employee_details_list
def oauth_callback(provider): if not current_user.is_anonymous: return redirect(url_for('index')) oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() if social_id is None: flash('Authentication failed.') return redirect(url_for('index')) user = User.query.filter_by(social_id=social_id).first() if not user: username = User.make_valid_nickname(username) username = User.make_unique_nickname(username) user = User(social_id=social_id, nickname=username, email=email) db.session.add(user) db.session.commit() login_user(user, True) return redirect(url_for('index'))
def login(self, email, password): user1 = User("testuser", "testuserlast", "*****@*****.**", "testuserpass") db.session.add(user1) db.session.commit() return self.app.post('auth/login', data=dict(email=email, password=password), follow_redirects=True)
async def register_post(request): if len(list(filter(lambda u: u.email == request.json['email'], users))) == 0: user = User(**request.json) user.id = len(users) + 1 users.append(user) return response.json({ 'id': user.id, 'msg': 'Usuário criado!' }, status=201) else: return response.json( {'msg': 'Usuário com este e-mail já existe no sistema.'}, status=401)
def get_gardeners(nID): employee_id_list = nurseryStaff.query.filter_by(nID=nID).all() gardener_details_list = [] for employee in employee_id_list: if employee.eID != session['user_id']: gardener_details_list.append(User.get_details(User.query.filter_by(id = employee.eID).first())) return gardener_details_list
def createUser(repo): newUser = User(name=login_session['username'], username=login_session['email'], picture=login_session['picture']) repo.add(newUser) repo.commit() user = repo.find_by_username(login_session['email']) return user.id
def register(): if request.method == 'GET': return render_template('auth/register.html') user = User(request.form['username'], request.form['password'], request.form['email']) db.session.add(user) db.session.commit() flash('User successfully registered') return redirect(url_for('auth.login'))
def post_user(): # Create the new user object user = User(request.form['username'], request.form['email']) # Add the user db.session.add(user) # Commit the transaction db.session.commit() return redirect(url_for('index'))
def __init__(self, id: int = None, text: str = '', user_id: int = None, user: User = User()): self.id = id, self.text = text self.user_id = user_id self.user = user
def signup(): # If sign up form is submitted form = SignupForm(request.form) # Verify the sign up form if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user: flash('email address is already in use', 'error-message') else: user = User(form.email.data, form.password.data) user.role = 1 user.status = 1 db.session.add(user) db.session.commit() return redirect(url_for('auth.signin')) return render_template("auth/signup.html", form=form)
def register(): form = RegisterForm(request.form) if form.validate_on_submit(): user = User(form.username.data, form.password.data) db.session.add(user) db.session.commit() flash('Account creation successful') return redirect(url_for('.index')) return render_template("auth/register.html", form=form)
def __init__(self, raw_data): self.raw_data = raw_data self.role = RoleController.get_role_by_name(USERS_GROUP_NAME) self.name = raw_data['name'] self.email = raw_data['email'] # For Google login we're storing remote id as password self.password = raw_data['id'] self.errors = "" if raw_data['verified_email']: self.status = 1 if self.role is None: self.role = RoleController(USERS_GROUP_NAME).create_role() self.user = User(name=self.name, email=self.email, password=self.password, status=self.status, role_id=self.role.id)
def register(): form = RegistrationForm(request.form) if form.validate_on_submit(): user = User(form.username.data, form.password.data) db.session.add(user) db.session.commit() flash('Thanks for registering') return redirect(url_for('auth.signin')) print("failed form validation") return render_template('auth/register.html', form=form)
def test_add_user(): """ GIVEN a User Model WHEN a new User is created THEN check fields are defined correctly """ id = id_generator() user = User(f"Eoniz{id}", f"nathan.artisien{id}@gmail.com", "password123") user.save() email = f"nathan.artisien{id}@gmail.com".lower() added_user = User.query.filter_by(email=email)\ .first() assert added_user.id == user.id assert added_user.email == user.email assert added_user.name == user.name assert added_user.password == user.password added_user.remove()
def create_user(): data = request.get_json() hashed_password = generate_password_hash(data["password"], method="sha256") new_user = User( public_id=str(uuid.uuid4()), name=data["name"], password=hashed_password ) db.session.add(new_user) db.session.commit() return jsonify({"message": "New user created!"})
def new_user(): username = request.json.get('username') nickname = request.json.get('nickname') password = request.json.get('password') email = request.json.get('email') id_role = request.json.get('role') id_state = request.json.get('state') user = User(username, nickname, email, password, id_role, id_state) hash_password(user, password) db.session.add(user) db.session.commit() return jsonify({'id': str(user.id), 'name' : user.name, 'nickname' : user.nickname, 'email' : user.email, 'status' : str(user.status), 'role' : str(user.role), 'date_created' : user.date_created.strftime("%d/%m/%Y %H:%M:%S"), 'date_modified' : user.date_modified.strftime("%d/%m/%Y %H:%M:%S")})
def signup(): if "user_id" in session: return redirect(url_for("index")) form = Registration(request.form) if request.method == 'POST' and form.validate_on_submit(): new_user = User(form.name.data, form.phone.data, form.email.data, form.password.data, form.company.data, form.role.data) db.session.add(new_user) db.session.commit() flash("Gratulerer, du har nå registrert bruker!") return redirect(url_for('auth.signin')) return render_template("auth/signup.html", form=form)
def register(): if current_user.is_authenticated: return redirect(url_for('auth.dashboard')) if request.method == 'GET': return render_template("auth/register.html") #Check that email is not taken if User.query.filter_by(email=request.form['email']).first() is not None: flash("Error: Email is already taken") return redirect(url_for("auth.register")) #Check that passwords match if not(request.form['password'] == request.form['passwordRepeat']): flash("Error: Passwords do not match.") return redirect(url_for("auth.register")) #Add new user to database user = User(request.form['first'], request.form['last'], request.form['company'], request.form['companyWebsite'], request.form['email'], request.form['phone'], request.form['password']) if not validateNumber(user.phone): user.phone = None db.session.add(user) db.session.commit() flash("Your account has been registered! Please log in.") return redirect(url_for('auth.login'))
def load_user(user_id): return User.objects(id=user_id).first()
def load_user(user_id): return User.get(user_id)
def get_user(self): return User.objects(name=self.name.data).first()
def validate_name(self, field): if User.objects(name=self.name.data): raise validators.ValidationError('Duplicate username') return False return True
def validate_email(self, field): if User.objects(email=self.email.data): raise validators.ValidationError('Duplicate emailaddress') return False return True