def create_user(self): new_user = User( user_id='Michael', authenticated=False, ) new_user.hash_password('password') db.session.add(new_user) db.session.commit()
def create_admin(): username = "******" password = "******" email = "*****@*****.**" user = User(username, password, email) user.admin = True db.session.add(user) db.session.commit()
def register(): email = request.json.get('email') password = request.json.get('password') if User.query.filter_by(email=email).first() is not None: status = 'user already registered' user = User(email=email) user.hash_password(password) db.session.add(user) db.session.commit() status = 'success' db.session.close() return jsonify({'result':status})
def register(): form = RegisterForm() if form.validate_on_submit(): user = User( name=form.username.data, email=form.email.data, password=form.password.data ) db.session.add(user) follow_self = user.follow(user) db.session.add(follow_self) db.session.commit() login_user(user) return redirect(url_for('home.home')) return render_template('register.html', form=form)
def favour_propos_user(user_id): form = CheckAccessTokenForm() if not form.validate_on_submit(): return generate_error_response(form.errors) return generate_data_response(json.dumps([p.as_dict() for p in User.get_favour_propos(user_id)]))
def verify_password(username_or_token, password): # first try to authenticate by token user = User.verify_auth_token(username_or_token) if not user: # try to authenticate with username/password user = User.query.filter_by(email=username_or_token).first() if not user or not user.verify_password(password): return False g.user = user return True
def create_user(email: str, nick_name: str, first_name: str, last_name: str, register_type: int) -> User: user = User() user.email = email user.nick_name = nick_name user.first_name = first_name user.last_name = last_name user.register_type = register_type return user
def test_users_cannot_complete_tasks_that_are_not_created_by_them(self): self.create_user() self.login('Michael', 'python') self.app.get('tasks/', follow_redirects=True) self.create_task() self.logout() new_user = User(name='Fletcher', email='*****@*****.**', password=bcrypt.generate_password_hash('python101')) db.session.add(new_user) db.session.commit() self.login('Fletcher', 'python101') self.app.get('tasks/', follow_redirects=True) response = self.app.get("complete/1/", follow_redirects=True) self.assertNotIn( b'The task is complete. Nice.', response.data ) self.assertIn( b'You can only update tasks that belong to you.', response.data )
def apiregister(): data = {} if request.headers['Content-Type'] == 'application/json': user = User(email=request.json['email'], password=request.json['password'], name=request.json['username'], confirmed=True, user_token=generate_password_hash( request.json['email'].encode())) db.session.add(user) db.session.commit() token = generate_confirmation_token(user.email) login_user(user) data['response'] = "success" # return "registered: %s %s you need to confirm"%(request.json['email'], request.json['password']) return json.dumps(data) else: data['response'] = "failure" return json.dumps(data)
def register(): error = None form = RegisterForm(request.form) if request.method == 'POST': if form.validate_on_submit(): new_user = User(form.name.data, form.email.data, bcrypt.generate_password_hash(form.password.data)) try: db.session.add(new_user) db.session.commit() flash("Thanks for registering. Please login.") return redirect(url_for('users.login')) except IntegrityError: error = """Oh no! That username and/or email already exists. Please try again.""" return render_template('register.html', form=form, error=error) else: return render_template('register.html', form=form, error=error) elif request.method == 'GET': return render_template('register.html', form=form)
def signup(): form = UserForm(request.form) if request.method == "POST": if form.validate(): try: new_user = User( form.first_name.data, form.last_name.data, form.username.data, form.password.data, ) db.session.add(new_user) db.session.commit() login_user(new_user) flash('User Created!') return redirect(url_for('users.index')) except IntegrityError as e: flash("Username already taken") return render_template('users/signup.html', form=form) return render_template('users/signup.html', form=form)
def register(): if current_user.is_authenticated: return redirect(url_for('posts.home')) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User( username=form.username.data, email=form.email.data, password=hashed_password, ) db.session.add(user) db.session.commit() flash(f'Your account has been created! You are now able to log in.', 'success') return redirect(url_for('users.login')) return render_template('register.html', form=form)
def page_forgot_password(): user = None form = ForgotPasswordForm() if form.validate_on_submit(): user = User.generate_password_reset_token(form.email_address.data) if user != None: send_password_reset_token(user.email_address, user.password_request_token) return redirect( url_for('user_views.page_forgot_password_request_processed')) else: flash( 'We can not find a user with that email address please try again.', 'danger') return render_template('v1/user/forgot-password.html', form=form, user=user)
def register(): form = RegisterForm(request.form) if request.method == 'POST': if form.validate_on_submit(): new_user = User(form.name.data, form.email.data, bcrypt.generate_password_hash(form.password.data)) user_exist = db.session.query(User).filter_by( name=new_user.name).first() email_exist = db.session.query(User).filter_by( email=new_user.email).first() if user_exist: form.name.errors.append('Username already taken') if email_exist: form.email.errors.append('Email already in use') if not (user_exist or email_exist): db.session.add(new_user) db.session.commit() flash('Thank you for registering. Please Login') return redirect(url_for('users.login')) return render_template('register.html', form=form)
def register(): error = None form = RegisterForm(request.form) if request.method == 'POST': if form.validate_on_submit(): new_user = User( form.name.data, form.email.data, form.password.data ) try: db.session.add(new_user) db.session.commit() flash('Thanks for registering. Please login to confirm.') redirect(url_for('users.login')) except IntegrityError: error = 'That username and/or email already exists.' return render_template('register.html', form=form, error=error) return render_template('register.html', form=form, error=error)
def init_database(): db.drop_all() db.create_all() for i in range(0, 100): db.session.add(User('User' + str(i + 1), 'a' + str(i + 1))) for j in range(0, 10): db.session.add(Image(get_image_url(), i + 1)) for k in range(0, 3): db.session.add( Comment('This is a comment' + str(k), 1 + 10 * i + j, i + 1)) db.session.commit() for i in range(50, 100, 2): user = User.query.get(i) user.username = '******' + user.username User.query.filter_by(id=51).update({'username': '******'}) db.session.commit() for i in range(50, 100, 2): comment = Comment.query.get(i + 1) db.session.delete(comment) db.session.commit() print 1, User.query.all() print 2, User.query.get(3) print 3, User.query.filter_by(id=5).first() print 4, User.query.order_by(User.id.desc()).offset(1).limit(2).all() print 5, User.query.filter(User.username.endswith('0')).limit(3).all() print 6, User.query.filter(or_(User.id == 88, User.id == 99)).all() print 7, User.query.filter(and_(User.id > 88, User.id < 93)).all() print 8, User.query.filter(and_(User.id > 88, User.id < 93)).first_or_404() print 9, User.query.order_by(User.id.desc()).paginate(page=1, per_page=10).items user = User.query.get(1) print 10, user.images image = Image.query.get(1) print 11, image, image.user
def signup(): form = NewUserForm(request.form) if request.method == 'POST': if form.validate(): username = request.form.get('username') password = request.form.get('password') first_name = request.form.get('first_name') last_name = request.form.get('last_name') admin = False new_user = User(username, password, first_name, last_name, admin) db.session.add(new_user) try: db.session.commit() login_user(new_user) return redirect(url_for('users.index')) except IntegrityError as err: flash('Username already exists.') return render_template('users/signup.html', form=form) return render_template('users/signup.html', form=form)
def register(): error = None form = RegisterForm(request.form) print(form.errors) if request.method == 'POST': if form.validate_on_submit(): details = Details(city=form.city.data, age=form.age.data, last=form.lastname.data, first=form.firstname.data) db.session.add(details) user = User(email=form.email.data, password=form.password.data) db.session.add(user) db.session.commit() login_user(user) flash("You were just logged in!") return redirect(url_for('account.account')) else: error = "Submission Failed" return render_template("register.html", form=form, error=error) return render_template("register.html", form=form, error=error)
def generate_post(): content = request.form email = content["email"] user = User.query.filter_by(email=email).first() if not user: user = User(email=email, login_count=0) db.session.add(user) db.session.flush() token = MagicTokenHandler.generate_token(user.email) db.session.add(token) db.session.commit() EmailHandler.send_email(user.email, "token_template.html", body={"token": token.token}) return render_template("generate.html", token=token.token, email=user.email)
def test_unread_message(self): u1 = User(username="******", email="*****@*****.**") u2 = User(username="******", email="*****@*****.**") db.session.add_all([u1, u2]) first_msg = Message(author=u1, recipient=u2, body="first message") db.session.add(first_msg) db.session.commit() self.assertEqual(u2.new_messages(), 1) second_msg = Message(author=u1, recipient=u2, body="second message") db.session.add(second_msg) db.session.commit() self.assertEqual(u2.new_messages(), 2) u2.last_message_read_time = datetime.utcnow() self.assertEqual(u2.new_messages(), 0)
def new_login(): new_user = User(public_id=session['user_id'], user_email=session['username']) token = jwt.encode( { 'publc_id': new_user.publc_id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60) }, app.config['SECRET_KEY']) db.session.add(new_user) db.session.commit() current_user = User.query.filter_by(public_id=session['user_id']).first() newFyleToken = Fyle_Tokens(updated_at=datetime.datetime.utcnow(), user_id=current_user.id, username=session['username'], tokens=json.dumps(session['res_text'])) db.session.add(newFyleToken) db.session.commit() return jsonify({ 'token': token.decode('UTF-8'), 'user_id': current_user.public_id })
def fill_user(): empty_user() # use Faker to generate users. num_users_to_generate = 100 fake = Faker() for i in range(num_users_to_generate): temp_username = fake.unique.last_name() + str(i) temp_password = '******' temp_hashed_pw = bcrypt.generate_password_hash(temp_password).decode( 'utf-8') temp_email = fake.unique.email() temp_user = User(username=temp_username, password=temp_hashed_pw, email=temp_email) db.session.add(temp_user) #db.session.execute('INSERT INTO "user" (username, password, email) VALUES (:param1, :param2, :param3);', {'param1': makeUsers.unique.last_name() + str(i), 'param2': '$2b$12$8oFObtgF/omzn/5jD0YSpe.ZphcX2G3lqqym9drbwZjJE7o6ubMmi', 'param3': makeUsers.unique.email()}) db.session.commit() fake.unique.clear( ) # see https://faker.readthedocs.io/en/master/index.html?highlight=unique#unique-values return
def get(self): # get the auth token auth_header = request.headers.get('Authorization') if auth_header: try: auth_token = auth_header.split(" ")[1] except IndexError: responseObject = { 'status': 'fail', 'message': 'Bearer token malformed.' } return make_response(jsonify(responseObject)), 401 else: auth_token = '' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): user = User.query.filter_by(id=resp).first() responseObject = { 'status': 'success', 'data': { 'user_id': user.id, 'email': user.email, 'admin': user.admin, 'registered_on': user.registered_on } } return make_response(jsonify(responseObject)), 200 responseObject = { 'status': 'fail', 'message': resp } return make_response(jsonify(responseObject)), 401 else: responseObject = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return make_response(jsonify(responseObject)), 401
def signup_post(email, name, password): #email = request.form.get('email') #name = request.form.get('name') #password = request.form.get('password') user = User.query.filter_by(email=email).first( ) # if this returns a user, then the email already exists in database if user: # if a user is found, we want to redirect back to signup page so user can try again flash('Email address already exists') return redirect(url_for('auth.signup')) # create new user with the form data. Hash the password so plaintext version isn't saved. new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256')) # add the new user to the database db.session.add(new_user) db.session.commit() return redirect(url_for('auth.login'))
def show(id): form = NewForm(request.form) user = User.query.filter_by(id = id).first() if request.method == b'PATCH': if form.validate(): edit_user = User.new_for_form(form) user.username = edit_user.username user.email = edit_user.email user.first_name = edit_user.first_name user.last_name = edit_user.last_name db.session.add(user) db.session.commit() return redirect(url_for('users.index')) else: return render_template('users/edit.html', form=form , user=user) if request.method == b'DELETE': db.session.delete(user) db.session.commit() return redirect(url_for('users.index')) user = User.query.filter_by(id = id).first() return render_template('users/user.html', user=user, id=id)
def AddNewUser(): form = AddNewUserForm() form.customer.choices=[(customer.id, customer.name) for customer in Customer.query.all()] print(form) print(request.method) blnError=None blnSuccess=None if request.method=="GET": return render_template('admin/AddNewUser.html',newUserForm=form) if form.validate_on_submit() : username = form.username.data email = form.email.data password = generateRandomPwd() customerid = form.customer.data firstname = form.firstname.data lastname = form.lastname.data isadmin = form.isAdmin.data salesForceID = form.salesForceID.data print(isadmin) exists = db.session.query(User.id).filter((User.salesForceID==salesForceID)|(User.username==username)).first() is not None print("exists="+str(exists)) if(exists): blnError=True blnSuccess=False flash("Username and/or SalesForce ID already exists!") #return render_template('admin/AddNewCampaign.html',newCampaignForm=form,success=False,error=True) else: hashed_password = generate_password_hash(password, method='sha256') new_user = User(username=username, email=email, password=hashed_password,customerid=customerid,firstname=firstname,lastname=lastname,isAdmin=isadmin,salesForceID=salesForceID) print(new_user) db.session.add(new_user) db.session.commit() sendGridEmail(email,"newuser",username,password) blnSuccess=True blnError=False return render_template('admin/AddNewUser.html',newUserForm=form,success=blnSuccess,error=blnError) else: print(form.errors) return render_template('admin/AddNewUser.html',newUserForm=form)
def add_user(): """Add a single user""" post_data = request.get_json() response_object = {'status': 'fail', 'message': 'Invalid payload.'} if not post_data: return jsonify(response_object), 400 username = post_data.get('username') email = post_data.get('email') try: user = User.query.filter_by(email=email).first() if not user: db.session.add(User(username=username, email=email)) db.session.commit() response_object['status'] = 'success' response_object['message'] = f'{email} was added!' return jsonify(response_object), 201 else: response_object['message'] = 'Sorry. That email already exists.' return jsonify(response_object), 400 except exc.IntegrityError as e: db.session.rollback() return jsonify(response_object), 400
def student_home(): assignments = Assignment_Posted.query.all() users = User.query.all() assignment_form = AssignmentSubmissionForm() squad = [] user = User() updates = Update.query.all() # if request.method == 'POST': # file = request.files['inputFile'] # if assignment_form.validate_on_submit(): # assignment_file = Assignment_Received(name=file.filename, data=file.read()) # db.session.add(assignment_file) # db.session.commit() # flash(format('Assignment sent successfully!'), 'success') return render_template('student_home.html', user=user, users=users, assignments=assignments, updates=updates, assignment_form=assignment_form)
def reset_password(token): if current_user.is_authenticated: return redirect(url_for('welcome')) user = User.verify_token_reset_password(token) if not user: app.logger.info( "Password reset token mismatch found, redirected to welcome page") return redirect(url_for('welcome')) form = PasswordResetForm() if form.validate_on_submit(): user.set_password(form.password.data) user.lockout = False user.fail_count = 0 db.session.commit() flash('Your password has been reset!') app.logger.info("Password has been reset for User[{}]".format( user.username)) return redirect(url_for('login')) return render_template('resetPwd.html', form=form)
def handle_login(req): try: user = User.query.filter(User.username == req['username']).first() if (not user): new_user = User(username=req['username']) db.session.add(new_user) db.session.commit() user = User.query.filter(User.username == req['username']).first() session['user_id'] = user.id session['username'] = user.username result = {'data': {'username': session['username']}} emit('logged-in', result) except: result = { 'error': { 'type': 'login error', 'message': 'something went wrong with logging you in to the chat app. try reloading the webpage and logging in later!' } } emit('logged-in', result)
def register(): form = AddUserForm(request.form) if request.method == 'POST': if form.validate_on_submit(): new_user = User( form.name.data, bcrypt.generate_password_hash( form.password.data).decode('utf-8'), form.email.data) # new_user = User(form.name.data, form.password.data, form.email.data) try: db.session.add(new_user) db.session.commit() flash('Registered Successfully. Login Now') return redirect(url_for('users.login')) except IntegrityError: error = 'Email already exists.' return render_template('register.html', form=form, error=error) else: flash('Invalid Form Data') return render_template('register.html', form=form)
def post(self): # get auth token auth_header = request.headers.get('Authorization') if auth_header: auth_token = auth_header.split(" ")[1] else: auth_token = '' if auth_token: resp = User.decode_auth_token(auth_token) if not isinstance(resp, str): # mark the token as blacklisted blacklist_token = BlacklistToken(token=auth_token) try: # insert the token db.session.add(blacklist_token) db.session.commit() responseObject = { 'status': 'success', 'message': 'Successfully logged out.' } return make_response(jsonify(responseObject)), 200 except Exception as e: responseObject = { 'status': 'fail', 'message': e } return make_response(jsonify(responseObject)), 200 else: responseObject = { 'status': 'fail', 'message': resp } return make_response(jsonify(responseObject)), 401 else: responseObject = { 'status': 'fail', 'message': 'Provide a valid auth token.' } return make_response(jsonify(responseObject)), 403
def register(): error = None form = RegisterForm(request.form) if 'logged_in' in session: return redirect(url_for('tweets.tweet')) if request.method == 'POST': if form.validate_on_submit(): new_user = User( form.name.data, form.email.data, bcrypt.generate_password_hash(form.password.data), ) try: db.session.add(new_user) db.session.commit() cache.delete_memoized(all_users) flash('Thanks for registering. Plese login.') return redirect(url_for('users.ui_login')) except IntegrityError: error = 'That username and/or email already exists.' return render_template('register.html', form=form, error=error) return render_template('register.html', form=form, error=error)
def reset_token(token): if current_user.is_authenticated: return redirect(url_for("main.home")) user = User.verify_reset_token(token) if user is None: flash(u"That is an invalid or expired token", "warning") return redirect(url_for('users.reset_request')) form = ResetPasswordForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user.password = hashed_password db.session.commit() flash(u'Your password has been updated! You are now able to log in!', "success") return redirect(url_for('users.login')) return render_template("reset_token.html", title='Reset Password', form=form)
def create_app(testing=False): app = Flask(__name__) if testing: app.config.from_object("project.config.TestingConfig") else: app.config.from_object("project.config.Config") with app.app_context(): from .views import api from .views import errors from project.models import User, Pace db.init_app(app) ma.init_app(app) cors.init_app(app) db.drop_all() db.create_all() db.session.commit() with open("data/users.csv", "r") as f: for line in f.readlines(): id, username, age, gender = line.strip().split(",") db.session.add( User(id=id, username=username, age=age, gender=gender)) db.session.commit() with open("data/pace.csv", "r") as f: for line in f.readlines(): user_id, total_time, distance = line.strip().split(",") db.session.add( Pace(user_id=user_id, total_time=total_time, distance=distance)) db.session.commit() app.register_blueprint(api.api_bp) app.register_blueprint(errors.error_bp) return app
def register(): error = None form = RegisterForm(request.form) if request.method == "POST": if form.validate_on_submit(): new_user = User(name=form.name.data, email=form.email.data, password=bcrypt.generate_password_hash( form.password.data)) try: db.session.add(new_user) db.session.commit() flash("You have been succesfully registered. Please login.") return redirect(url_for("users.login")) except IntegrityError: error = """That username and/or email address is already in use. Please try again.""" return render_template("register.html", error=error, form=form) else: error = "Something gone wrong. Try again." return render_template("register.html", error=error, form=form) return render_template("register.html", form=form)
def edit_user(user_id): new_id = user_id error = None form = RegisterForm(request.form) open_user = User.query.filter_by(id=new_id) if request.method == 'POST': if form.validate_on_submit(): ed_user = User(form.fio.data, form.adress.data, form.phone.data, form.name.data, form.email.data, bcrypt.generate_password_hash(form.password.data)) try: db.session.update(ed_user) db.session.commit() flash('Thanks for registering. Please login.') return redirect(url_for('users.login')) except IntegrityError: error = 'That username and/or email already exist.' # if session['role'] == 'admin': return render_template('edit_user.html', form=form, error=error, open_user=open_user)
def test_User_default_representation(self): new_user = User(name='Mikosan', email='*****@*****.**', password='******') self.assertEqual(new_user.__repr__(), '<User Mikosan>')
def migrate_user(): from projectl.models import User as Ul from project.models import User as Um for i in Ul.query.all(): u = Um(password='******') u.id = i.id u.username = i.username u.first_name = i.first_name u.last_name = i.last_name u.department = i.department u.position = i.position u.local_number = i.local_number u.password = i.password u.email = i.email u.active = i.active u.password = i.password u.active = i.active db.session.add(u) db.session.commit()
def signup(): """ Signup --- tags: - user parameters: - name: body in: body description: info for signup required: true schema: id: UserSignup required: - name - email - password - phone - student_id - university properties: name: type: string example: honey email: type: string example: [email protected] password: type: string example: baby123 minLength: 3 maxLength: 32 phone: type: string Length: 11 example: 09371234567 pattern: ^09[0-9]{9}$ student_id: type: string Length: 8 example: 93522222 university: type: string enum: ['iust', 'sharif', 'tehran', 'other'] example: iust national_code: type: string Length: 10 example: 4361234567 responses: 201: description: Successfully registered 400: description: Bad request 406: description: unique info already exists """ json = request.json email = json['email'] if User.query.filter_by(email=email).first(): return jsonify(errors='email already exists'), 406 try: user_obj = User() user_obj.populate(json) db.session.add(user_obj) db.session.commit() except IntegrityError as err: db.session.rollback() if "name" in str(err.orig): print "name already exists" return "name already exists", 406 elif "phone" in str(err.orig): print "phone already exists" return "phone already exists", 406 elif "student_id" in str(err.orig): print "student_id already exists" return "student_id already exists", 406 return jsonify(), 201
instruct1 = "Hello! Welcome to my kitchen.|Today I am going to teach you how to cook the sliced cold chicken.|Cut a chicken to small pieces|add|add|Boil the chicken for 10 mins|Poul out all the water|add|Cut the greenonions|add|Congratuations! You have finished learning this dish!" instruct2 = "Hello! Welcome to my kitchen.|Today I am going to teach you how to cook the Sichuan fish.|add|add|add|Fry 5min|add|Boil for 10mins.|add|Boil for 6mins|Congratuations! You have finished learning this dish!" instruct3 = "Hello! Welcome to my kitchen.|Today I am going to teach you how to cook the bitter shrimp ball.|Slice the bitter melon and put it at the bottom.|add|add|add|Steam for 20mins|add|Congratuations! You have finished learning this dish!" recipe1 = Recipe(id=1,recipename="sliced_cold_chicken", ingresorder="2 5 6 7", instruction = instruct1) recipe2 = Recipe(id=2,recipename="sichuan_fish", ingresorder="11 10 1 5 4", instruction = instruct2) recipe3 = Recipe(id=3,recipename="bitter_shrimp_ball", ingresorder="8 3 9 7", instruction = instruct3) recipe4 = Recipe(id=4,recipename="crystal_shrimp", ingresorder="1", instruction = " ") recipe5 = Recipe(id=5,recipename="buddha_Jumps_over_the_wall", ingresorder="1", instruction = " ") recipe6 = Recipe(id=6,recipename="steamed_preserved_hams", ingresorder="1", instruction = " ") recipe7 = Recipe(id=7,recipename="phoenix_peony_stew", ingresorder="1", instruction = " ") recipe8 = Recipe(id=8,recipename="jellyfish_with_vinegar", ingresorder="1", instruction = " ") recipe1.add_ingres([ingre2, ingre5, ingre6, ingre7]) recipe2.add_ingres([ingre4, ingre1, ingre5, ingre11, ingre10]) recipe3.add_ingres([ingre8, ingre3, ingre9, ingre7]) user1 = User( username = "******", password = "******") user2 = User( username = "******", password = "******") user1.add_recipes([ recipe1 , recipe3, recipe2, recipe4, recipe5, recipe6, recipe7, recipe8 ]) user2.add_recipes([ recipe2 , recipe1 ]) # commit the changes db.session.commit()
__author__ = 'admin' from project import db from project.models import Post, User from datetime import date db.create_all() db.session.add(Post('First post', 'this is my first post','Welcome', date(2014, 10, 03), None, 1, 'Mike')) user = User(user_id='admin', authenticated=False) user.hash_password('password') db.session.add(user) db.session.commit()
def check_user(form, field): if User.getuser_by_token(field.data) is None: raise ValidationError(errors.UNATHORIZED)