def setUp(self): print("Setup...") UserSQL.create_table() self.test_user1 = User(id=1, userID='admin', password='******', admin=True) self.test_user2 = User(id=2, userID='user', password='******', admin=False) UserSQL.insert(self.test_user1) UserSQL.insert(self.test_user2)
def selectByUserID(userID): # Connect to database db = pymysql.connect(host=HOST, user=USER, passwd=PASSWD, db=DATABASE) cursor = db.cursor() # SQL command sql = """SELECT * FROM `User` \ WHERE `User`.userID = %(userID)s""" params = {"userID": userID} users = [] try: # Execute the SQL command cursor.execute(sql, params) results = cursor.fetchall() for row in results: id, userID, password, admin = row[0], row[1], row[2], row[3] user = User(id, userID, password, admin) users.append(user) except Exception as error: print("Unable to fetch data: ", error) # disconnect from server db.close() return users
def put(self): user = current_user() data, _ = UserSchema().load(request.get_json(), instance=User.lookup(user.email), partial=True) db.session.commit() return {'status': 'success', 'msg': f'User {id} successfully updated'}
def register(): form = RegisterForm(request.form) if form.validate_on_submit(): user = User(email=form.email.data, firstName=form.firstName.data, lastName=form.lastName.data, workPlace=form.workPlace.data, gender=form.gender.data, dateOfBirth=form.dateOfBirth.data, category=form.category.data, title=form.title.data, country=form.country.data, password=form.password.data, confirmed=False) db.session.add(user) db.session.commit() token = generate_confirmation_token(user.email) confirm_url = url_for('user.confirm_email', token=token, _external=True) html = render_template('user/activate.html', confirm_url=confirm_url) subject = "Please confirm your email" send_email(user.email, subject, html) login_user(user) flash('A confirmation email has been sent via email.', 'success') return redirect(url_for("user.unconfirmed")) return render_template('user/register.html', form=form)
def validate_user(self, data, **kwargs): errors = [] if 'email' in data: if data['email'] == "": errors.append("Please provide an email") elif "@" not in data['email']: errors.append("Please provide a valid email") if User.lookup(data['email']): errors.append("User with that email already exists") if 'password' in data: if data['password'] == "": errors.append("Please provide a password") elif len(data['password']) < 6: errors.append( "Please provide a password of minimum 6 characters") if 'first_name' in data: if data['first_name'] == "": errors.append("Please provide a first name") if 'last_name' in data: if data['last_name'] == "": errors.append("Please provide a last name") if errors: raise ValidationError(errors)
def post(self): try: data, _ = UserSchema().load(request.get_json()) id = User.add(data) except ValidationError as err: return {'status': 'error', 'errors': err.messages['_schema']}, 403 return {'status': 'success', 'msg': f'successfully created user {id}'}
def test_insert(self): print("Testing insert...") test_user = User(0, "dpham", "password", False) UserSQL.insert(test_user) users = UserSQL.selectAll() self.assertEqual(len(users), 3)
def create_admin(): """Creates the admin user.""" db.session.add( User(email="*****@*****.**", password="******", admin=True, confirmed=True, confirmed_on=datetime.datetime.now())) db.session.commit()
def object_decoder(obj): if '__type__' in obj: if obj['__type__'] == 'User': return User(obj['userID'], obj['password'], obj['admin']) elif obj['__type__'] == 'Ticket': return Ticket(obj['id'], obj['userID'], obj["room"], obj["title"], obj["description"], obj["start"], obj["end"], obj["timestamp"]) return obj
def init_database(): db.create_all() u1 = User("First", "Last", "*****@*****.**", guard.encrypt_password("wow"), "20/4/1990", "", "Male") db.session.add(u1) db.session.commit() yield db db.drop_all()
def populate_users(): with open('data/people.json') as f: data = json.load(f) for person in data: u = User(first_name=person['first_name'], last_name=person['last_name'], email=person['email'], avatar=person['avatar'], password=person['password'], dob=datetime.strptime(person['dob'], '%d/%m/%Y'), gender=person['gender'], description=person['description'], university=person['university']) db.session.add(u) db.session.commit()
def login(): form = LoginForm() if form.validate_on_submit(): user = User.find_by_email(form.email.data) if user is not None and user.check_password(form.password.data): login_user(user) flash("მომხმარებელმა წარმატებით გაიარა ავტორიზაცია") next = request.args.get('next') if next is None: next = url_for('welcome') return redirect(next) return render_template('login.html', form=form)
def registration(): form = RegistrationForm() if form.validate_on_submit(): user = User( email=form.email.data, username=form.username.data, password=form.password.data, ) db.session.add(user) db.session.commit() flash("რეგისტრაცია წარმატებით დასრულდა") return redirect(url_for('user.login')) return render_template('registration.html', form=form)
async def signup(data: SignUpSchema, db: Session = Depends(get_db)): error_dict = dict() # checking email user_email_objects = db.query(User).filter(User.email == data.email).first() if user_email_objects: error_dict['email'] = messages['email_exists'] # checking username username_objects = db.query(User).filter(User.username == data.username).first() if username_objects: error_dict['username'] = messages['username_exists'] if error_dict: raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=error_dict) obj = User(**data.__dict__) db.add(obj) db.commit() db.refresh(obj) return {'message': messages['signup_success']}
def setUp(self): db.create_all() user = User(email="*****@*****.**", password="******", paid=False) db.session.add(user) db.session.commit()
import sys sys.path.append("..") from project.user.models import User from database import UserSQL UserSQL.create_table() test_user1 = User(id=1, userID='admin', password='******', admin=True) test_user2 = User(id=2, userID='user', password='******', admin=False) UserSQL.insert(test_user1) UserSQL.insert(test_user2)
def validate_email_from_db(self, email): temp_email = self.email.data if User.find_by_email(temp_email): raise ValidationError("Email already exists")