def create_user(): """Allows creating a user""" data = request.get_json() or {} if (('username' not in data) or ('email' not in data) or ('name' not in data) or ('organisation' not in data) or ('password' not in data) or ('admin' not in data) or ('reviewer' not in data)): return bad_request( 'must include username, email, name, organisation, password and admin fields' ) if User.query.filter_by(username=data['username']).first(): return bad_request('please use a different username') if User.query.filter_by(email=data['email']).first(): return bad_request('please use a different email address') try: data['admin'] = bool(strtobool(data['admin'])) except ValueError: return bad_request('admin is not boolean') try: data['reviewer'] = bool(strtobool(data['reviewer'])) except ValueError: return bad_request('reviewer is not boolean') user = User() user.from_json(data, admin=True) db.session.add(user) db.session.commit() response = jsonify(user.to_json(admin=True)) response.status_code = 201 return response
def test_expired_confirmation_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_confirmation_token(1) time.sleep(2) self.assertFalse(u.confirm(token))
def register(): """Registration page""" if current_app.config['DISABLE_PUBLIC_REGISTRATION']: abort(403) elif current_user.is_authenticated: return redirect(url_for('home.index')) if check_setup(): flash('Please complete initial setup first', 'info') return redirect(url_for('auth.initial_setup')) form = RegistrationForm() del form.admin # Hides option to make user admin del form.reviewer # Hides option to make user admin if current_app.config['CAPTCHA_ENABLED'] is False: del form.recaptcha if form.validate_on_submit(): user = User(name=form.name.data, organisation=form.organisation.data, username=form.username.data, email=form.email.data, admin=False, reviewer=False) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('auth.login')) return render_template('auth/register.html', title='Register', form=form)
def test_valide_reset_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_reset_token() self.assertTrue(u.reset_password(token, 'dog')) self.assertTrue(u.verify_password('dog'))
def test_invalid_confirmation_token(self): u = User(password='******') u2 = User(password='******') db.session.add(u) db.session.add(u2) db.session.commit() token = u.generate_confirmation_token() self.assertFalse(u2.confirm(token))
def get(self): john = User(name="abc1234dacxa") john.save() post = Post(post_string="a12dbc") post.save() return {"hello": "world"}
def add_admin(self): with app.app_context(): u = User(username='******', role=ROLES['admin'], email='*****@*****.**') u.set_password('admin') db.session.add(u) db.session.commit()
def add_user(self): with app.app_context(): u = User(username='******', role=ROLES['user'], email='*****@*****.**') u.set_password('user') db.session.add(u) db.session.commit()
def test_invalid_reset_token(self): u = User(password='******') u2 = User(password='******') db.session.add(u) db.session.add(u2) db.session.commit() token = u.generate_reset_token() self.assertFalse(u2.reset_password(token, 'horse')) self.assertTrue(u2.verify_password('dog'))
def update_user(user: User, data: Dict, session: Session): user = query_user(username, session) try: user.username = data['username'] user.email = data['email'] user.image = '../../media/' + data['image'] user.password_hash = data['password'] except KeyError as e: raise SessionError('Insufficient data to update user info. ' + str(e))
def post(self): """ Create user account""" data = request.get_json() or {} user = User() try: user.from_dict(data) except Exception as error: return error_response(error, 400) db.session.add(user) db.session.commit() return make_response(jsonify(user.to_dict()), 201)
def create_user(db, username, email, name, organisation, admin, reviewer, password): u = User(username=username, email=email, name=name, organisation=organisation, admin=admin, reviewer=reviewer) u.set_password(password) db.session.add(u) db.session.commit() return u
def register(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash("Registration Successful!") return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)
def get_test_placeholder_user(): return User(username='******', email='*****@*****.**', password='******', full_name='FakeName', language_id=1, telegram_id='666666')
def get(self): """ Read information of all users. Note : Cannot read information of users with higher role""" parser.parse_args() current_user = User.query.get(get_jwt_identity()) page = request.args.get('page', 1, type=int) per_page = request.args.get('per_page', current_app.config['USERS_PER_PAGE'], type=int) if per_page > current_app.config['USERS_PER_PAGE']: per_page = current_app.config['USERS_PER_PAGE'] where_stmt = request.args.get('filter', "") if len(where_stmt) > 0: where_stmt = 'WHERE role<=%d AND (%s)' % (current_user.role, where_stmt) else: where_stmt = 'WHERE role<=%d' % current_user.role (users, total) = filter_users(current_app, User.table_schema, 'user', where_stmt, page, per_page) total_pages = ceil(total / per_page) data = User.to_dict_collection(users, page, per_page, total_pages) if total > page * per_page: data['next_page'] = page + 1 if page > 1: data['prev_page'] = page - 1 return make_response(jsonify(data), 200)
async def signup(body: RequestBody, response: Response): username = body.username name = body.name password_hash = hashlib.sha256(str.encode(body.password)).hexdigest() # Check if username already exists exists = db.query(User).filter_by(username=username).first() if exists: response.status_code = status.HTTP_409_CONFLICT return {"result": "fail", "reason": "Username already taken"} user = User(username=username, name=name, password_hash=password_hash) db.add(user) db.commit() payload = { "exp": datetime.utcnow() + timedelta(days=0, hours=24), "iat": datetime.utcnow(), "iss": username, } token = jwt.encode(payload, ACCESS_TOKEN_KEY, algorithm="HS256") content = {"result": "ok"} response = JSONResponse(content=content) response.headers["X-AUTH-TOKEN"] = f"{token}" return response
def seed_users(count): from app.database.repositories import UserRepo from app import di from app.database.models import User, Profile from app.database.repositories import ProfileRepo user_repo: UserRepo = di.get(UserRepo) profile_repo: ProfileRepo = di.get(ProfileRepo) count = int(count) time = datetime.now().strftime('%d%m%y%H%M%S') with click.progressbar(length=count, show_percent=True, show_eta=True, show_pos=True) as bar: for idx in bar: user = User(email=f"{idx}@{time}.com", password=generate_password_hash(fake.password())) user_repo.save(user) profile_repo.save( Profile(first_name=fake.first_name(), last_name=fake.last_name(), interests=fake.paragraph(), birth_date=fake.date_of_birth().strftime('%Y-%m-%d'), gender=choice(['male', 'female']), city_id=randint(1, 10), user_id=user.id)) db.commit()
def post(self): login_data = self.parse_args() # Both username and password have to be supplied if not login_data.get('username') or not login_data.get('password'): return 'Username and password needed', 400 duplicate_user = User.query.filter_by( username=login_data.get('username')).first() # Username must be unique if duplicate_user: return 'Username already exists', 409 # Passwords should not be stored in their raw string form but rather hashed. secure_password = self.set_password( password=login_data.get('password')) new_user = User(username=login_data.get('username'), password=secure_password) self.save(new_user) auth_token = self.generate_token(new_user.username) return {'auth_token': auth_token}, 201
def user(): return User(username='******', email='*****@*****.**', password='******', full_name='test me', language_id=1 )
def create_user(session): user = User(username='******', email='*****@*****.**', password='******', language_id=1) session.add(user) session.commit() return user
def create_admin(): from app.database.models import User admin = User(username='******', password='******', level=User.LEVEL.ADMIN, user_type=User.USER_TYPE.LOCAL) db.session.add(admin) db.session.commit()
def add_users(cls): ed_user = User(name='ssssssssssssss', fullname='Ed sssss', nickname='ssssssss') manager.session.add(ed_user) #pour l instant a delete manager.commit()
def user(session): faker = Faker() user1 = User(username=faker.first_name(), email=faker.email()) session.add(user1) session.commit() yield user1 session.delete(user1) session.commit()
def register(): """Registration page""" check_permissions() form = RegistrationForm() del form.recaptcha if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data, name=form.name.data, organisation=form.organisation.data, admin=bool(form.admin.data), reviewer=bool(form.reviewer.data)) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('User registed successfully') return redirect(url_for('admin.admin')) return render_template('auth/register.html', title='Register', form=form)
def get_placeholder_user(): return User( username='******', email='*****@*****.**', password='******', full_name='My Name', language_id=1, telegram_id='', )
def get_test_placeholder_user() -> User: return User( username="******", email="*****@*****.**", password="******", full_name="FakeName", language_id=1, telegram_id="666666", )
def create_new_user(data): print(data["username"]) role = Role.query.filter_by(id=1).first() hashed_password = generate_password_hash(data["password"], method="sha256") user = User(username=data["username"], email=data["email"], password=hashed_password, role=role) db.session.add(user) db.session.commit()
def create_user(username: str, password: str, email: str, language_id: int, session: Session) -> User: """Creates and saves a new user.""" user = User(username=username, password=password, email=email, language_id=language_id) save(session, user) return user
def post(self): """ Authorise user and provide access token""" username = request.json.get('username') password = request.json.get('password') user = User.find_by_username(username) if not user: return error_response('Username does not exist', 401) if not user.check_password(password): return error_response('Incorrect password', 401) access_token = create_access_token(identity=user.id) return make_response(jsonify(access_token = access_token), 201)
def add_user(cls): ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname') manager.session.add(ed_user) our_user = manager.session.query(User).filter_by(name='ed').first() #on commit la session manager.session.commit() #les operation de recherche dans la sb manager.querry() manager.querry2() #pour l instant a delete manager.commit()
class EditForm(FlaskForm): first_name = StringField('Voornaam') last_name = StringField('Achternaam') username = StringField('Gebruikersnaam', validators=[DataRequired()]) email = StringField('Email') level = SelectField('Niveau', validators=[DataRequired()], choices=User.get_zipped_levels()) user_type = SelectField('Type', validators=[DataRequired()], choices=User.get_zipped_types()) id = IntegerField(widget=HiddenInput()) change_password = SelectField('Paswoord aanpassen', choices=[('False', 'Neen'), ('True', 'Ja')]) password = PasswordField('Paswoord') confirm_password = PasswordField('Bevestig Paswoord') def validate_password(self, field): if self.user_type.data == User.USER_TYPE.LOCAL: if self.change_password.data == 'True': if field.data == '': raise ValidationError('Paswoord invullen aub') else: field.data = None else: field.data = None def validate_confirm_password(self, field): if self.user_type.data == User.USER_TYPE.LOCAL and self.password.data: if field.data != self.password.data: raise ValidationError('Beide paswoorden moeten hetzelfde zijn') else: field.data = None def validate_username(self, field): user = User.query.filter( User.username == func.binary(field.data)).first() if user and (not self.id.data or self.id.data and self.id.data != user.id): raise ValidationError('Gebruikersnaam is reeds in gebruik')
def test_valid_confirmation_token(self): u = User(password='******') db.session.add(u) db.session.commit() token = u.generate_confirmation_token() self.assertTrue(u.confirm(token))
def test_password_verification(self): u = User(password='******') self.assertTrue(u.verify_password('cat')) self.assertFalse(u.verify_password('dog'))