def profile(): # oddly needed for lookup user = cdw.users.with_id(current_user.get_id()) threads = cdw.get_threads_started_by_user(current_user)[:5] all_posts = cdw.posts.with_fields(author=user).order_by('-created') debates = [] for p in all_posts: try: debates.append(cdw.threads.with_firstPost(p)) except: pass more_posts = len(all_posts) - 10 more_debates = len(debates) - 10 return render_template("profile.html", section_selector="profile", page_selector="index", threads=threads, posts=all_posts[:10], debates=debates[:10], more_posts=more_posts, more_debates=more_debates)
def apikeysdelete(id): apikey = db.Apikey() # we need to check that the apikey id belongs to this user key = apikey.user_has_access_to_apikey(unicode(current_user.get_id()), id) if key == None: flash('You do not have access to that apikey!') return redirect(url_for('apikeys')) # Check that this won't leave them without a apikey keys = apikey.find_by_user(unicode(current_user.get_id())) if keys.count() == 1: flash('You can\'t delete all your keys... else whats the point? You \ need to keep at least one at all times.') return redirect(url_for('apikeys')) return render_template('apikeysdelete.html', name=key['name'], id=id)
def register_photo(): # If they set their phone number see if they used the kiosk # and use their photograph found_kiosk_image = False if current_user.phoneNumber and len(current_user.phoneNumber) > 1: current_app.logger.debug('The user set their phone number during ' 'the registration process. Check to see ' 'if they have used the kiosk before.') # Find the first kiosk user with the same phone number user = cdw.users.with_id(current_user.get_id()) kiosk_user = cdw.users.with_fields(origin="kiosk", phoneNumber=current_user.phoneNumber).first() if kiosk_user: current_app.logger.debug("Found a kiosk user with the same " "phone number. Check if the images " "have been uploaded to S3 yet...") import urllib2 from boto.s3.connection import S3Connection try: image_url = '%s/media/images/web/%s.jpg' % (current_app.config['MEDIA_ROOT'], str(kiosk_user.id)) image2_url = '%s/media/images/thumbnails/%s.jpg' % (current_app.config['MEDIA_ROOT'], str(kiosk_user.id)) current_app.logger.debug("Checking if %s exists" % image_url) urllib2.urlopen(image_url) current_app.logger.debug("Checking if %s exists" % image2_url) urllib2.urlopen(image2_url) aws_conf = current_app.config['CDW']['aws'] key_id = aws_conf['access_key_id'] secret_key = aws_conf['secret_access_key'] bucket_name = aws_conf['s3bucket'] conn = S3Connection(key_id, secret_key) bucket = conn.get_bucket(bucket_name) source_web_key = 'media/images/web/%s.jpg' % str(kiosk_user.id) source_thumb_key = 'media/images/thumbnails/%s.jpg' % str(kiosk_user.id) new_web_key = 'images/users/%s-web.jpg' % str(user.id) new_thumb_key = 'images/users/%s-thumbnail.jpg' % str(user.id) current_app.logger.debug("Copying web image %s to %s" % (source_web_key, new_web_key)) bucket.copy_key(new_web_key, bucket_name, source_web_key, preserve_acl=True) current_app.logger.debug("Copying thumbnail image %s to %s" % (source_thumb_key, new_thumb_key)) bucket.copy_key(new_thumb_key, bucket_name, source_thumb_key, preserve_acl=True) current_app.logger.debug("Setting user image") current_user.webProfilePicture = user.webProfilePicture = '%s-web.jpg' % str(user.id) current_user.webProfilePictureThumbnail = user.webProfilePictureThumbnail = '%s-thumbnail.jpg' % str(user.id) user.save() found_kiosk_image = True except Exception, e: current_app.logger.warn("Unable to copy kiosk image for " "web user: %s" % e)
def logout(): """ Log the user out. """ current_app.logger.debug('Logging out user') current_app.logger.debug('current user id:' + current_user.get_id()) logout_user() flash(u"Logged out.") return redirect(url_for('index'))
def to_question(self): try: category = cdw.categories.with_id(self.category.data) except: category = None return SuggestedQuestion( author=cdw.users.with_id(current_user.get_id()), category=category, text=self.question.data)
def to_question(self): try: category = cdw.categories.with_id(self.category.data) except: category = None return SuggestedQuestion(author=cdw.users.with_id( current_user.get_id()), category=category, text=self.question.data)
def messagesarchive(id): # we need to check that the message id belongs to this user message = db.Message() m = message.user_has_access_to_message(unicode(current_user.get_id()), id) if m == None: flash('You do not have access to that apikey!') return redirect(url_for('dashboard')) message.archive(id) return redirect(url_for('dashboard'))
def apikeysdeleteconfirmed(id): # we need to check that the apikey id belongs to this user apikey = db.Apikey() key = apikey.user_has_access_to_apikey(unicode(current_user.get_id()), id) if key == None: flash('You do not have access to that apikey!') return redirect(url_for('apikeys')) apikey.delete(id) flash('The apikey has been deleted') return redirect(url_for('apikeys'))
def apikeyscreate(): form = ApikeyscreateForm(request.form) if request.method == 'POST' and form.validate(): apikey = db.Apikey() apikey.name = form.name.data apikey.key = apikey.random_key() apikey.userid = unicode(current_user.get_id()) apikey.save() # all good, lets go to the dashboard with a flash flash('Your apikey has been created.') return redirect(url_for('apikeys')) return render_template('apikeyscreate.html', form=form)
def messagescreate(): form = MessagescreateForm(request.form) if request.method == 'POST' and form.validate(): message = db.Message() message.level = form.level.data message.heading = form.heading.data message.blurb = form.blurb.data message.body = form.body.data message.userid = unicode(current_user.get_id()) message.apikeyid = unicode(form.apikeyid.data) message.save() # all good, lets go to the dashboard with a flash flash('Your message has been created.') return redirect(url_for('dashboard')) return render_template('messagescreate.html', form=form)
def remove_all_connections(provider_id): try: display_name = get_display_name(provider_id) connection_service.remove_all_connections( current_user.get_id(), provider_id) current_app.logger.debug('Removed all connections to %s for ' '%s' % (provider_id, current_user)) flash("Connections to %s removed" % display_name) except: current_app.logger.error('Unable to remove all connections to ' '%s for %s' % (get_display_name(provider_id), current_user)) flash("Unabled to remove connection") return redirect(request.referrer)
def save_form(): ID = request.form['id'] if not ID: raise Exception("no id") if not allowed_knowl_id.match(ID): flask.flash("""Oops, knowl id '%s' is not allowed. It must consist of lower/uppercase characters, no spaces, numbers or '.', '_' and '-'.""" % ID, "error") return flask.redirect(url_for(".index")) k = Knowl(ID) k.title = request.form['title'] k.content = request.form['content'] k.quality = request.form['quality'] k.timestamp = datetime.now() k.save(who=current_user.get_id()) return flask.redirect(url_for(".show", ID=ID))
def get_connection_values(self, response=None): api = twitter.Api(consumer_key=self.consumer_key, consumer_secret=self.consumer_secret, access_token_key=response['oauth_token'], access_token_secret=response['oauth_token_secret']) user = api.VerifyCredentials() return None if response == None else { "user_id": current_user.get_id(), "provider_id": self.provider_id, "provider_user_id": user.id, "access_token": response['oauth_token'], "secret": response['oauth_token_secret'], "display_name": '@%s' % user.screen_name, "profile_url": "http://twitter.com/%s" % user.screen_name, "image_url": user.profile_image_url }
def save_form(): ID = request.form['id'] if not ID: raise Exception("no id") if not allowed_knowl_id.match(ID): flask.flash( """Oops, knowl id '%s' is not allowed. It must consist of lower/uppercase characters, no spaces, numbers or '.', '_' and '-'.""" % ID, "error") return flask.redirect(url_for(".index")) k = Knowl(ID) k.title = request.form['title'] k.content = request.form['content'] k.quality = request.form['quality'] k.timestamp = datetime.now() k.save(who=current_user.get_id()) return flask.redirect(url_for(".show", ID=ID))
def remove_all_connections(provider_id): try: display_name = get_display_name(provider_id) connection_service.remove_all_connections( current_user.get_id(), provider_id) current_app.logger.debug('Removed all connections to %s for ' '%s' % (provider_id, current_user)) flash("Connections to %s removed" % display_name) except: current_app.logger.error( 'Unable to remove all connections to ' '%s for %s' % (get_display_name(provider_id), current_user)) flash("Unabled to remove connection") return redirect(request.referrer)
def get_connection_values(self, response): if response: access_token = response['access_token'] graph = facebook.GraphAPI(access_token) profile = graph.get_object("me") p_url = "http://facebook.com/profile.php?id=%s" % profile['id'] i_url = "http://graph.facebook.com/%s/picture" % profile['id'] return { "user_id": current_user.get_id(), "provider_id": self.provider_id, "provider_user_id": profile['id'], "access_token": access_token, "secret": None, "display_name": profile['username'], "profile_url": p_url, "image_url": i_url } return None
def comment(post_id=None): """ Creates a comment for a blog post. GET - Displays comment form if user is logged in. POST - Writes comment to database. """ form = CommentForm(request.form) post = g.db_session.query(Post).filter_by(id=post_id).first() if request.method == 'POST' and form.validate(): comment = Comment(form.content.data, current_user.get_id(), post.id) g.db_session.add(comment) return redirect(url_for('blog.view_post', post_id=post_id)) try: return render_template('comment_new.html', form=form, post=post) except TemplateNotFound: abort(404)
def new(): """ Create a new blog post. """ error = None form = BlogPostForm(request.form) if request.method == 'POST' and form.validate(): new_blog_post = Post(form.title.data, form.content.data, form.published.data, current_user.get_id()) g.db_session.add(new_blog_post) flash('New Blog Post Created!') return redirect(url_for('blog.show_posts')) try: return render_template('blog_new.html', form=form, error=error) except TemplateNotFound: abort(404)
def job_detail(job_id): job = Job.query.get_or_404(job_id) if job.status == 'INITIALIZING': flash('The job has been created and is currently initializing. Once ' \ 'initialization is complete, this page will show login information. ' \ 'Please wait about 30 seconds and refresh the page manually.') if request.method == 'GET': if app.debug: app.logger.debug('rendering detail for job %d' % job_id) log_files = [] try: log_files = os.listdir('%s/test-%d' % (app.config['LOG_LOCATION'], job.id)) except OSError: app.logger.warn('No logs found for job %d' % job.id) # if the job isn't running, don't bother getting the slot information slot = None if job.status in ['RUNNING', 'INSTALLING']: slot = job.machine.slot return render_template('detail_job.html', job = job, log_prefix = app.config['LOG_PREFIX'], logs = log_files, slot=slot) if request.method == 'POST': if not (current_user.admin or current_user.get_id() == job.user.id): app.logger.warn('User %s (id: %d) tried to modify job %d (owner: %s, id: %d)' % (current_user.username, current_user.get_id(), job.id, job.user.username, job.user.id)) flash('You need admin priviliges to make changes to this job.') return redirect(url_for('job.job_detail', job_id=job_id)) if app.debug: app.logger.debug('job %d received POST request %s' % (job_id, str(request.form))) if request.form['request']: machine_control = get_machine_control() if request.form['request'] == 'COMPLETE': app.logger.info('Completing job %d' % job_id) job.status = 'COMPLETE' job.machine.slot.active = False # now shutdown and delete the VM if job.machine.status not in ['STOPPED', 'DELETED']: machine_control.stop_machine(job.machine.name) job.machine.status = 'STOPPED' if job.machine.status != 'DELETED': machine_control.delete_machine(job.machine.name) machine_control.delete_disk(job.machine.name) job.machine.status = 'DELETED' db.session.add(job) db.session.add(job.machine.slot) db.session.add(job.machine) db.session.commit() if request.form['request'] == 'RESTART': machine_control.start_machine(job.machine.name) job.machine.status = 'RUNNING' db.session.add(job.machine) db.session.commit() return redirect(url_for('.job_detail', job_id=job_id))
def _get_current_user_primary_connection(self): return self._get_primary_connection(current_user.get_id())
def decorated_view(*args, **kwargs): logger.info("admin access attempt by %s" % current_user.get_id()) if not current_user.is_admin(): return flask.abort(403) # 401 = access denied return fn(*args, **kwargs)
def job_detail(job_id): job = Job.query.get_or_404(job_id) if job.status == 'INITIALIZING': flash('The job has been created and is currently initializing. Once ' \ 'initialization is complete, this page will show login information. ' \ 'Please wait about 30 seconds and refresh the page manually.') if request.method == 'GET': if app.debug: app.logger.debug('rendering detail for job %d' % job_id) log_files = [] try: log_files = os.listdir('%s/test-%d' % (app.config['LOG_LOCATION'], job.id)) except OSError: app.logger.warn('No logs found for job %d' % job.id) # if the job isn't running, don't bother getting the slot information slot = None if job.status in ['RUNNING', 'INSTALLING']: slot = job.machine.slot return render_template('detail_job.html', job=job, log_prefix=app.config['LOG_PREFIX'], logs=log_files, slot=slot) if request.method == 'POST': if not (current_user.admin or current_user.get_id() == job.user.id): app.logger.warn( 'User %s (id: %d) tried to modify job %d (owner: %s, id: %d)' % (current_user.username, current_user.get_id(), job.id, job.user.username, job.user.id)) flash('You need admin priviliges to make changes to this job.') return redirect(url_for('job.job_detail', job_id=job_id)) if app.debug: app.logger.debug('job %d received POST request %s' % (job_id, str(request.form))) if request.form['request']: machine_control = get_machine_control() if request.form['request'] == 'COMPLETE': app.logger.info('Completing job %d' % job_id) job.status = 'COMPLETE' job.machine.slot.active = False # now shutdown and delete the VM if job.machine.status not in ['STOPPED', 'DELETED']: machine_control.stop_machine(job.machine.name) job.machine.status = 'STOPPED' if job.machine.status != 'DELETED': machine_control.delete_machine(job.machine.name) machine_control.delete_disk(job.machine.name) job.machine.status = 'DELETED' db.session.add(job) db.session.add(job.machine.slot) db.session.add(job.machine) db.session.commit() if request.form['request'] == 'RESTART': machine_control.start_machine(job.machine.name) job.machine.status = 'RUNNING' db.session.add(job.machine) db.session.commit() return redirect(url_for('.job_detail', job_id=job_id))
def apikeys(): apikey = db.Apikey() apikeys = apikey.find_by_user(current_user.get_id()) return render_template('apikeys.html', apikeysactive=True, apikeys=apikeys)
def user_has_access_to_apikey(form, field): # Check to see if this user has access to this apikey apikey_search = db.apikeys.find_one({"userid": unicode(current_user.get_id()), "_id": ObjectId(field.data)}) if apikey_search == None: raise ValidationError("That apikey is invalid!")
def register_photo(): # If they set their phone number see if they used the kiosk # and use their photograph found_kiosk_image = False if current_user.phoneNumber and len(current_user.phoneNumber) > 1: current_app.logger.debug('The user set their phone number during ' 'the registration process. Check to see ' 'if they have used the kiosk before.') # Find the first kiosk user with the same phone number user = cdw.users.with_id(current_user.get_id()) kiosk_user = cdw.users.with_fields( origin="kiosk", phoneNumber=current_user.phoneNumber).first() if kiosk_user: current_app.logger.debug("Found a kiosk user with the same " "phone number. Check if the images " "have been uploaded to S3 yet...") import urllib2 from boto.s3.connection import S3Connection try: image_url = '%s/media/images/web/%s.jpg' % ( current_app.config['MEDIA_ROOT'], str(kiosk_user.id)) image2_url = '%s/media/images/thumbnails/%s.jpg' % ( current_app.config['MEDIA_ROOT'], str(kiosk_user.id)) current_app.logger.debug("Checking if %s exists" % image_url) urllib2.urlopen(image_url) current_app.logger.debug("Checking if %s exists" % image2_url) urllib2.urlopen(image2_url) aws_conf = current_app.config['CDW']['aws'] key_id = aws_conf['access_key_id'] secret_key = aws_conf['secret_access_key'] bucket_name = aws_conf['s3bucket'] conn = S3Connection(key_id, secret_key) bucket = conn.get_bucket(bucket_name) source_web_key = 'media/images/web/%s.jpg' % str( kiosk_user.id) source_thumb_key = 'media/images/thumbnails/%s.jpg' % str( kiosk_user.id) new_web_key = 'images/users/%s-web.jpg' % str(user.id) new_thumb_key = 'images/users/%s-thumbnail.jpg' % str( user.id) current_app.logger.debug("Copying web image %s to %s" % (source_web_key, new_web_key)) bucket.copy_key(new_web_key, bucket_name, source_web_key, preserve_acl=True) current_app.logger.debug( "Copying thumbnail image %s to %s" % (source_thumb_key, new_thumb_key)) bucket.copy_key(new_thumb_key, bucket_name, source_thumb_key, preserve_acl=True) current_app.logger.debug("Setting user image") current_user.webProfilePicture = user.webProfilePicture = '%s-web.jpg' % str( user.id) current_user.webProfilePictureThumbnail = user.webProfilePictureThumbnail = '%s-thumbnail.jpg' % str( user.id) user.save() found_kiosk_image = True except Exception, e: current_app.logger.warn("Unable to copy kiosk image for " "web user: %s" % e)
def dashboard(): message = db.Message() messages = message.find_by_user(current_user.get_id()) return render_template('dashboard.html', dashboardactive=True, messages=messages)