def register(): """Handle registration; show form or process results.""" form = RegisterForm() openid_form = OpenIDForm() if openid_form.validate_on_submit(): return oid.try_login( openid_form.openid.data, ask_for=['nickname', 'email'], ask_for_optional=['fullname'], ) if form.validate_on_submit(): new_user = User(username=form.username.data) new_user.set_password(form.username.data) db.session.add(new_user) db.session.commit() flash( "Your user has been created, please login.", category="success" ) return redirect(url_for('.login')) openid_errors = oid.fetch_error() if openid_errors: flash(openid_errors, category='danger') return render_template('register.html', form=form, openid_form=openid_form)
def register(): if current_user.is_authenticated: return redirect(url_for('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(_('Congratulations, you are now a registered user!')) return redirect(url_for('login')) return render_template('register.html', title=_('Register'), form=form)
def admin(request): if request.method == 'GET': if 'user' in request.session: if request.session['security_level'] == 10: Users = [] for user in User.objects(is_verify=False): Users.append(user) return render_to_response('admin.html', {'Users': Users} ,RequestContext(request)) return redirect(request, 'You are not admin', '') elif request.method == 'POST': d = request.POST uname = d['username'] User.objects(username=uname).update(set__is_verify=True) return redirect(request, '', 'admin', 0)
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db') self.app = app self.ctx = self.app.app_context() self.ctx.push() db.drop_all() db.create_all() u = User(username=self.default_username) u.set_password(self.default_password) db.session.add(u) db.session.commit() self.client = TestClient(self.app, u.generate_auth_token(), '')
def register(): if current_user.is_authenticated: return redirect(url_for('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('You have registered successfully!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def setup_users(): """Add users and roles.""" poster = Role(name="poster") admin = Role(name="admin") default = Role(name="default") db.session.add_all([poster, admin, default]) for username, roles in [("joel", [poster, admin]), ("george", [poster]), ("jane", [default])]: u = User(username=username, roles=roles) u.set_password("testtest") db.session.add(u) db.session.commit()
def admin(request): if request.method == 'GET': if 'user' in request.session: if request.session['security_level'] == 10: Users = [] for user in User.objects(is_verify=False): Users.append(user) return render_to_response('admin.html', {'Users': Users}, RequestContext(request)) return redirect(request, 'You are not admin', '') elif request.method == 'POST': d = request.POST uname = d['username'] User.objects(username=uname).update(set__is_verify=True) return redirect(request, '', 'admin', 0)
def post(self, post_id=None): if post_id: abort(400) else: args = post_post_parser.parse_args(strict=True) user = User.verify_auth_token(args['token']) if not user: abort(401) new_post = Post(title=args['title'], publish_date=datetime.datetime.now(), text=args['text'], user=user) if args['tags']: for item in args['tags']: tag = Tag.query.filter_by(title=item).first() # Add the tag if it exists. # If not, make a new tag if tag: new_post.tags.append(tag) else: new_tag = Tag(title=item) new_post.tags.append(new_tag) db.session.add(new_post) db.session.commit() return new_post.id, 201
def add_post(request): if request.method == 'GET': if 'user' in request.session: return render_to_response('add_post.html', RequestContext(request)) else: return redirect(request, 'You need to login to make a post', '') elif request.method == 'POST': d = request.POST title = d['title'] content = d['content'] date = datetime.datetime.now() viewable = d['viewable'] author = None for user in User.objects(username=request.session['user']): author = user form = UploadImgForm(request.POST, request.FILES) if form.is_valid(): newImg = Img(img_width=50, img_height=50) newImg.img_src.put(request.FILES['img'], content_type='image/jpeg') newImg.save() newPost = Post(title=title, content=content, date_added=date, image_id=newImg, author=author, viewable=viewable) newPost.save() return redirect(request, 'Added post successfully', '') return redirect(request, 'All inputs need to be filled', 'add_post')
def facebook_authorized(resp): if resp is None: return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description'] ) session['facebook_oauth_token'] = (resp['access_token'], '') me = facebook.get('/me') name = me.data['name'] id = me.data['id'] print "***", name, id user = User.query.filter_by(username=name).first() if not user: user = User(username=name) db.session.add(user) db.session.commit() # Login User here flash("You have been logged in.", category="success") return redirect( request.args.get('next') or url_for('blog.home') )
def register(request): if request.method == 'GET': return render_to_response('register.html',RequestContext(request)) elif request.method == 'POST': d = request.POST pword = d['password'] pword_repeat = d['password_repeat'] if pword == pword_repeat: uname = d['username'] for user in User.objects: if uname == user.username: return redirect(request, 'This user has existed', 'register') newuser = User(username=uname, password=pword) newuser.save() return redirect(request, 'Your account is registered successfully', 'login') else: return redirect(request, 'The passwords are not the same', 'register')
def test_login(self): """ Tests if the login form works correctly """ test_role = Role(name="default") db.session.add(test_role) db.session.commit() test_user = User(username="******") test_user.set_password("test") db.session.add(test_user) db.session.commit() result = self.client.post('/login', data=dict(username='******', password="******"), follow_redirects=True) self.assertEqual(result.status_code, 200) self.assertIn('You have been logged in', result.data)
def create_admin(): if request.method == 'POST': adminuser = User(email=request.form['email'], username=request.form['username'], password=request.form['password'], is_admin=True) db.session.add(adminuser) db.session.commit() return "create admin" return render_template('admin_signup.html')
def test_login(self): """ Tests if the login form works correctly """ test_role = Role(name="default") db.session.add(test_role) db.session.commit() test_user = User(username="******") test_user.set_password("test") db.session.add(test_user) db.session.commit() result = self.client.post('/login', data=dict( username='******', password="******" ), follow_redirects=True) self.assertEqual(result.status_code, 200) self.assertIn('You have been logged in', result.data)
def register(request): if request.method == 'GET': return render_to_response('register.html', RequestContext(request)) elif request.method == 'POST': d = request.POST pword = d['password'] pword_repeat = d['password_repeat'] if pword == pword_repeat: uname = d['username'] for user in User.objects: if uname == user.username: return redirect(request, 'This user has existed', 'register') newuser = User(username=uname, password=pword) newuser.save() return redirect(request, 'Your account is registered successfully', 'login') else: return redirect(request, 'The passwords are not the same', 'register')
def register(): if current_user.is_authenticated: return redirect(url_for('main.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 can able to Log in now','success') return redirect(url_for('users.login')) return render_template('register.html', title='Resgister', form=form)
def register(request): if request.method == 'GET': form = blogForm.register() return render(request, 'blogapp/register.html', {'form': form}) elif request.method == 'POST': form = blogForm.register(request.POST) if form.is_valid(): temp = models.User.objects.filter( userName=form.cleaned_data['userName']).exists() if temp == False: userModel = User() userModel.userName = form.cleaned_data['userName'] userModel.password = form.cleaned_data['password'] userModel.save() return HttpResponse('数据提交成功!快去登录吧.') else: error = '用户名已经存在,请换一个用户名试试!' return render(request, 'blogapp/register.html', { 'form': form, 'error': error }) else: return render(request, 'blogapp/register.html', {'form': form})
def register(): 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('Thanks for registering! Now you can login!') return redirect(url_for('users.login')) return render_template('register.html', form=form)
def reset_password(token): if current_user.is_authenticated: return redirect(url_for('index')) user = User.verify_reset_password_token(token) if not user: return redirect(url_for('index')) form = ResetPasswordForm() if form.validate_on_submit(): user.set_password(form.password.data) db.session.commit() flash(_('Your password has been reset.')) return redirect(url_for('login')) return render_template('reset_password.html', form=form)
def signup(): form = SignUpForm() # I learn how to manipulate the form from lecture 10 if form.validate_on_submit(): password_hash = generate_password_hash(form.password.data) # I learn how to add data to database from lecture 11 user = User(username=form.username.data, password_hash=password_hash, email=form.email.data) db.session.add(user) db.session.commit() session["USERNAME"] = user.username session['USERID'] = user.id return redirect(url_for('login')) return render_template('sign_up.html', form=form)
def register(): if current_user.is_authenticated: return redirect(url_for('home')) form = RegistrationForm() if form.validate_on_submit(): hased_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hased_password) db.session.add(user) db.session.commit() flash(f'Account Created for {form.username.data}!', 'green') return redirect(url_for('login')) return render_template('auth/register.html', title="Register", form=form)
def register(): if current_user.is_authenticated: return redirect(url_for('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('Twoje konto zostało utworzone! Możesz się zalogować', 'success') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
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('That is an invalid or expird 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(f'Your Password t has been Updated! You can able to Log in now','success') return redirect(url_for('users.login')) return render_template('reset_token.html', title='Reset Password', form=form)
def delete(self, post_id=None): if not post_id: abort(400) post = Post.query.get(post_id) if not post: abort(404) args = post_delete_parser.parse_args(strict=True) user = User.verify_auth_token(args['token']) if user != post.user: abort(403) db.session.delete(post) db.session.commit() return "", 204
def register(): if current_user.is_authenticated: return redirect(url_for("main.home")) form = RegistrationForm() if form.validate_on_submit(): user = User( username=form.username.data, email=form.email.data, password=form.password.data, ) db.session.add(user) db.session.commit() flash("Your account has been created! You are now able to log in", "success") return redirect(url_for("users.login")) return render_template("register.html", title="Register", form=form)
def test_follow(self): u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') db.session.add(u1) db.session.add(u2) db.session.commit() self.assertEqual(u1.followed.all(), []) self.assertEqual(u1.followers.all(), []) u1.follow(u2) db.session.commit() self.assertTrue(u1.is_following(u2)) self.assertEqual(u1.followed.count(), 1) self.assertEqual(u1.followed.first().username, 'susan') self.assertEqual(u2.followers.count(), 1) self.assertEqual(u2.followers.first().username, 'john') u1.unfollow(u2) db.session.commit() self.assertFalse(u1.is_following(u2)) self.assertEqual(u1.followed.count(), 0) self.assertEqual(u2.followers.count(), 0)
def register(): if current_user.is_authenticated: return redirect(url_for('home')) form = RegForm() if form.validate_on_submit(): userm = User.query.filter_by(email=form.email.data).first() usern = User.query.filter_by(username=form.username.data).first() if userm is None and usern is None: hashedPassword = bcrypt.generate_password_hash(form.password.data).decode('utf-8') newUser = User(username=form.username.data, email=form.email.data, password=hashedPassword) db.session.add(newUser) db.session.commit() flash('Account created successfully', 'success') return redirect(url_for('login')) else: flash('Account with that name or email already exists', 'danger') return render_template('register.html', title='Register', form=form)
def register(): if current_user.is_authenticated: return redirect(url_for('main.home')) form = RegistrationForm() if form.validate_on_submit(): hashed_pw = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hashed_pw) db.session.add(user) db.session.commit() # Bootstrap categozization of flash includes success flash('Your account has been created.', 'success') return redirect(url_for('users.login')) return render_template('register.html', title='Register', form=form)
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("That is an invalid or exipred token", "warning") return redirect(url_for("users.reset_request")) form = ResetPasswordForm() if form.validate_on_submit(): user.password = form.password.data db.session.add(user) db.session.commit() flash("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 twitter_authorized(resp): if resp is None: return 'Access denied: reason: {} error: {}'.format( request.args['error_reason'], request.args['error_description'] ) session['twitter_oauth_token'] = resp['oauth_token'] + resp['oauth_token_secret'] user = User.query.filter_by(username=resp['screen_name']).first() if not user: user = User(username=resp['screen_name']) db.session.add(user) db.session.commit() # Login User here flash("You have been logged in.", category="success") return redirect( request.args.get('next') or url_for('blog.home') )
def signup(): form = SignupForm() if form.validate_on_submit(): if form.password.data != form.password2.data: flash('Passwords do not match!') return redirect(url_for('signup')) user_in_db = User.query.filter( User.username == form.username.data).first() if user_in_db: flash('Username already existed!') return redirect(url_for('signup')) passw_hash = generate_password_hash(form.password.data) user = User(username=form.username.data, email=form.email.data, password_hash=passw_hash) db.session.add(user) db.session.commit() flash('User registered with username:{}'.format(form.username.data)) session["USERNAME"] = user.username return redirect(url_for('login')) return render_template('signup.html', title='Register a new user', form=form)
def put(self, post_id=None): print "PUT", post_id if not post_id: abort(400) post = Post.query.get(post_id) if not post: abort(404) args = post_put_parser.parse_args(strict=True) user = User.verify_auth_token(args['token']) if not user: abort(401) if user != post.user: abort(403) if args['title']: post.title = args['title'] if args['text']: post.text = args['text'] if args['tags']: for item in args['tags']: tag = Tag.query.filter_by(title=item).first() # Add the tag if it exists. If not, make a new tag if tag: post.tags.append(tag) else: new_tag = Tag(item) post.tags.append(new_tag) db.session.add(post) db.session.commit() return post.id, 201
def add_post(request): if request.method == 'GET': if 'user' in request.session: return render_to_response('add_post.html', RequestContext(request)) else: return redirect(request, 'You need to login to make a post', '') elif request.method == 'POST': d = request.POST title = d['title'] content = d['content'] date = datetime.datetime.now() viewable = d['viewable'] author = None for user in User.objects(username=request.session['user']): author = user form = UploadImgForm(request.POST, request.FILES) if form.is_valid(): newImg = Img(img_width = 50, img_height=50) newImg.img_src.put(request.FILES['img'], content_type = 'image/jpeg') newImg.save() newPost = Post(title=title, content=content, date_added=date, image_id=newImg, author=author, viewable=viewable) newPost.save() return redirect(request, 'Added post successfully', '') return redirect(request, 'All inputs need to be filled', 'add_post')
def test_follow(self): u1 = User(nickname='john', email='*****@*****.**') u2 = User(nickname='susan', email='*****@*****.**') db.session.add(u1) db.session.add(u2) db.session.commit() assert u1.unfollow(u2) is None u = u1.follow(u2) db.session.add(u) db.session.commit() assert u1.follow(u2) is None assert u1.is_following(u2) assert u1.followed.count() == 1 assert u1.followed.first().nickname == 'susan' assert u2.followers.count() == 1 assert u2.followers.first().nickname == 'john' u = u1.unfollow(u2) assert u is not None db.session.add(u) db.session.commit() assert not u1.is_following(u2) assert u1.followed.count() == 0 assert u2.followers.count() == 0
def test_follow_posts(self): # create four users u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') db.session.add_all([u1, u2, u3, u4]) # create four posts now = datetime.utcnow() p1 = Post(body="post from john", author=u1, timestamp=now + timedelta(seconds=1)) p2 = Post(body="post from susan", author=u2, timestamp=now + timedelta(seconds=4)) p3 = Post(body="post from mary", author=u3, timestamp=now + timedelta(seconds=3)) p4 = Post(body="post from david", author=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup the followers u1.follow(u2) # john follows susan u1.follow(u4) # john follows david u2.follow(u3) # susan follows mary u3.follow(u4) # mary follows david db.session.commit() # check the followed posts of each user f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() f3 = u3.followed_posts().all() f4 = u4.followed_posts().all() self.assertEqual(f1, [p2, p4, p1]) self.assertEqual(f2, [p2, p3]) self.assertEqual(f3, [p3, p4]) self.assertEqual(f4, [p4])
def test_avatar(self): u = User(nickname='john', email='*****@*****.**') avatar = u.avatar(128) expected = 'http://www.gravatar.com/avatar/d4c74594d841139328695756648b6bd6' assert avatar[0:len(expected)] == expected
def test_avatar(self): u = User(username='******', email='*****@*****.**') self.assertEqual(u.avatar(128), ('https://www.gravatar.com/avatar/' 'd4c74594d841139328695756648b6bd6' '?d=identicon&s=128'))
from blogapp import create_app from blogapp.models import db, User, Role app = create_app('blogapp.config.TestConfig') db.app = app db.create_all() default = Role(name="default") poster = Role(name="poster") db.session.add(default) db.session.add(poster) db.session.commit() test_user = User(username="******") test_user.set_password("test") test_user.roles.append(poster) db.session.add(test_user) db.session.commit() app.run(port=5001, use_reloader=False)