Exemple #1
0
def new_post():
    if (current_user.role != 'desk'):
        return render_template('auth/accessDenied.html')

    if request.method == 'POST':
        patient_ssnId = request.form['ssnId']
        patient_name = request.form['name']
        patient_age = request.form['age']
        patient_admissionDate = request.form['admissionDate']
        patient_bedType = request.form['bedType']
        patient_address = request.form['address']
        patient_city = request.form['city']
        patient_state = request.form['state']
        newPatient = Patient(ssnId=patient_ssnId,
                             name=patient_name,
                             age=patient_age,
                             admissionDate=patient_admissionDate,
                             bedType=patient_bedType,
                             address=patient_address,
                             city=patient_city,
                             state=patient_state)
        db.session.add(newPatient)
        db.session.commit()
        flash('Patient created')
        return redirect('/patients')
    else:
        return render_template('deskExec/newPatient.html')
Exemple #2
0
def settings(user):
    sett = global_settings.find().next(
    ) if global_settings.count() != 0 else {}
    admin_email = sett.get('email', None)
    web_title = sett.get('title', None)

    # check if user is an admin
    admin = global_database.find_one(ids['user'], username=user, fsr=True)

    if admin is not None:
        # admin saving changes
        if request.args.get('wave') is not None:
            # update the global setting
            global_settings.update({}, {
                '$set': {
                    'wave': int(request.args['wave']),
                    'diss': int(request.args['dis']),
                    'email': request.args['admin_email'],
                    'email_pass': request.args['admin_pass'],
                    'title': request.args['web_title'],
                    'max_tags': request.args['max_tags']
                }
            })

            flash('Successfully saved changes')

        return render_template('pages/settings.html',
                               set=sett,
                               email=admin_email,
                               title=web_title)
    else:
        flash("page dose not exist....")
        return redirect('/')
Exemple #3
0
def registrarLogs():
    arquivo = open('auth.log')
    # print(arquivo.read())
    cont = 0
    for linhas in arquivo.readlines():
        print(linhas.split())
        dataString = linhas.split()[1] + "-" + linhas.split(
        )[0] + "-2020 " + linhas.split()[2]
        print(dataString)
        data = datetime.strptime(
            dataString, "%d-%b-%Y %H:%M:%S"
        )  # colocando data vindo do Log num padrao americano pra fazer insert no banco
        print(data)
        ip = linhas.split()[3]
        print(ip.replace("ip-", "").replace("-", "."))
        ipFormatado = ip.replace("ip-", "").replace("-", ".")  # formanto IP
        print(
            str(linhas.split()[4:]).replace("'", "").replace(",", "").replace(
                "[", "").replace("]", ""))
        mensagem = "{} {}".format(
            linhas.split()[4],
            str(linhas.split()[5:]).replace("'", "").replace(",", "").replace(
                "[", "").replace("]", "").rstrip(
                ))  # limpando o \n nas strings e no final de cada linha
        log = Log(data, ipFormatado,
                  mensagem)  # montando o objeto com os dados vindo do Log
        db.session.add(log)  # adicionando na tabela
        db.session.commit()
        if cont == 12500:
            break
        cont = cont + 1
    log = None
    flash('LOGS REGISTRADOS COM SUCESSO', "success")
    return redirect(url_for('api.listarTodos'))
def display_event(event_id):
    if 'user' in session or 'admin' in session:  # logged in
        e = EventsModel.query.filter_by(ID=event_id).first()
        if e is None:
            flash(f"Event  With ID : '{event_id}' Does Not Exist", 'success')
            print(f"Event  With ID : '{event_id}' Does Not Exist")
            return redirect(URL_PREFIX)
        else:
            users_interested = []
            num_interested = 0
            total_users_registered = 0
            if 'admin' in session:  # if admin in session then show names of interested users
                rs = UserModel.query.all()
                total_users_registered = len(rs)
                for i in rs:
                    if event_id in i.InterestedActivities:
                        users_interested.append([i.ID, i.Name])
                num_interested = len(users_interested)

            return render_template(
                'events/display-event-page.html',
                event=e,
                users_interested=users_interested,
                num_interested=num_interested,
                total_users_registered=total_users_registered)
    else:
        flash("Not Logged In", 'danger')
        print("Not Logged In")
        return redirect('/login')
def delete_event(event_id):
    if 'admin' in session:
        # delete event
        e = EventsModel.query.filter_by(ID=event_id).first()
        db.session.delete(e)

        # delete event from user's favourite events
        rs = UserModel.query.all()
        recipients = []
        for user in rs:
            if event_id in user.InterestedActivities:
                recipients.append(user.ID + '@bennett.edu.in')
                fav_events = user.InterestedActivities.replace(
                    event_id + ',', '')
                user.InterestedActivities = fav_events

        sendMail("Event Cancelled : " + e.EventHeading,
                 get_event_description(e), recipients,
                 "Mail Sent Successfully")

        # commit changes
        db.session.commit()

        flash(f"Event With ID : '{event_id}' Deleted Successfully", 'success')
        print(f"Event With ID : '{event_id}' Deleted Successfully")
        return redirect('/admin')
    else:
        flash("Admin Not Logged In", 'danger')
        print("Admin Not Logged In")
        return redirect('/login')
Exemple #6
0
def edit(user,title):
    # get all sections
    sec = global_database.query(ids['section'],
                                limit=global_database.count(ids['section']))

    all_sections = []

    # append all sections
    for section in sec:
        all_sections.append(section)

    # user editing the paper
    if request.method == "GET" and session['username']:
        # get the repo
        query = global_database.find_one(ids['repo'],username= user, title=title)

        return render_template('pages/edit.html',
                               query=query,
                               all_sections =all_sections
                               )
    # user update the paper
    else:
        # get date stars and avatar and validate data
        date, stars, avatar, pdf = validate(request)

        # get the old repo
        prev = repos.find_one({'username': user, 'title':title})

        # Api maximum limit has reached
        if isinstance(stars, dict) or isinstance(avatar, dict):
            # Flash the message
            flash(stars)
            # redirect to homepage
            return redirect('/')

        heroku = True if "heroku" in request.form.get('deploy', []) else False

        # get data from user
        content = {
            'username':session['username'],
            'title': request.form['title'],
            'new_title': request.form['title'] + "<curr>" + prev['title'],
            'url_repo': request.form['repo'],
            'url_pdf': pdf,
            'date': f'{date}',
            'description': request.form['desc'],
            'new_description':request.form['desc'] + "<curr>" + prev['description'],
            'star':stars,
            'avatar':avatar,
            'pending':True,
            'section': request.form['section'],
            'approved':False,
            'heroku':heroku
        }
        # update the repo
        repos.replace_one({'username': user, 'title':title}, content, True)

        # show success
        flash("Successfully updated the paper. now wait for admin to approve")
        return redirect(f'/{user}/profile')
def add_new_event():
    if 'admin' in session:  # can only add event if any admin is logged in
        form = AddEvent(request.form)
        if request.method == "POST" and form.validate():
            date = datetime.strptime(str(form.date.data),
                                     '%Y-%m-%d').strftime('%d/%m/%Y')
            time = str(form.time.data).strip().upper()
            venue = str(form.venue.data).strip().upper()
            heading = str(form.heading.data).strip()
            description = str(form.description.data).strip()

            random_id = generate_random_id()

            # add event to database
            e = EventsModel(random_id, heading, description, date, time, venue)
            db.session.add(e)
            db.session.commit()

            flash(f"Event Added Successfully With ID : '{random_id}'",
                  'success')
            print(f"Event Added Successfully With ID : '{random_id}'")
    else:
        flash("Admin Not Logged In", 'danger')
        print("Admin Not Logged In")
        return redirect('/login')
    return render_template("events/add-event.html", form=form)
def update(id):
    patient = Patient.query.get_or_404(id)
    if request.method == 'POST':
        patient_name = request.form['name']
        patient_age = request.form['age']
        patient_admissionDate = request.form['admissionDate']
        patient_bedType = request.form['bedType']
        patient_address = request.form['address']
        patient_city = request.form['city']
        patient_state = request.form['state']
        #VALIDATIONS******************
        if (len(patient_name) == 0 or len(str(patient_age)) == 0
                or len(patient_admissionDate) == 0 or len(patient_bedType) == 0
                or len(patient_address) == 0 or len(patient_city) == 0
                or len(patient_state) == 0):
            flash("No field must be empty!", "danger")
            return render_template('deskExec/update.html', patient=patient)
        patient.name = patient_name
        patient.age = patient_age
        patient.admissionDate = patient_admissionDate
        patient.bedType = patient_bedType
        patient.address = patient_address
        patient.city = patient_city
        patient.state = patient_state
        db.session.commit()
        flash('Patient details updated', 'success')
        return redirect('/patients')
    else:
        return render_template('deskExec/update.html', patient=patient)
Exemple #9
0
    def edit_student_profile():
        curr_user = User.query.filter(User.id == int(session['id'])).all()
        print(curr_user)
        if len(curr_user) != 1:
            flash('This offer not found.', 'info')
            return render_template("404.html"), 404

        curr_user = curr_user[0]

        import sys
        print('\n\n', curr_user, '\n\n')
        import sys
        print('\n\n' + str(dict(request.form)) + '\n\n')
        import json
        print('\n\n' + str(request.__dict__) + '\n\n')

        x = update_cv(session['id'], request.form['name'],
                      request.form['email'], request.form['telephone'],
                      request.form['location'], request.form['birthday'],
                      request.form['languages'], request.form['education'],
                      request.form['projects'], request.form['resume-content'],
                      request.form['skills'], request.form['hobbies'])
        print('\n\n' + str(x) + '\n\n')

        return my_redirect(url_for('core.profile'))
Exemple #10
0
def flash_editor_errors(form):
    for field, errors in form.errors.items():
        for error in errors:
            flash("В поле '%s'- ошибка: %s" % (
                getattr(form, field).label.text,
                error
            ))
Exemple #11
0
def signup():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        role = request.form['role']

        user = User.query.filter_by(username=username).first()

        if user:
            flash('user already exists', 'danger')
            return redirect('/signup')

        newUser = User(username=username,
                       password=generate_password_hash(password,
                                                       method='sha256'),
                       role=role)
        db.session.add(newUser)
        db.session.commit()

        # Use of flash to show appropriate messages....
        flash('user created', 'success')
        return redirect('/signup')

    else:
        return render_template('auth/signup.html')
Exemple #12
0
def addnewmed(ssn):
    if (current_user.role != 'pharm'):
        return render_template('auth/accessDenied.html')
    if request.method == "POST":
        medName = request.form['mname']
        reqQuant = request.form['quantity']
        requiredMed = Med.query.filter_by(mname=medName)[0]
        patId = Patient.query.filter_by(ssnId=ssn)[0].id
        # Checks medicine's availablility(if quantity is not zero)
        if (int(requiredMed.quantity) - int(reqQuant)) >= 0:
            medDict = {}
            medDict['medId'] = requiredMed.mid
            medDict['pid'] = patId
            medDict['name'] = medName
            medDict['quant'] = reqQuant
            medDict['rate'] = requiredMed.Rate
            medDict['amount'] = int(reqQuant) * int(requiredMed.Rate)
            newMed.append(medDict)
            print(medDict['name'])
            return redirect(url_for('patientmedinfo', ssn=ssn))
        else:
            flash(
                "Quantity not availaible. Available quantity of this medicine is {}"
                .format(requiredMed.quantity), "danger")
            return redirect(url_for('issuemedicine', ssn=ssn))
Exemple #13
0
def diagnosticinfo():
    if (current_user.role != 'diag'):
        return render_template('auth/accessDenied.html')
    if request.method == 'POST':
        search_ssnId = request.form['ssnId']
        try:
            searched_ssnId = int(search_ssnId)
        except:
            flash("Please Enter a valid Integer Id!", "danger")
            print("please enter an integer")
            return redirect('/diagnostic_dashboard')
        patient = Patient.query.filter_by(ssnId=search_ssnId).first()
        tests = Patientdiagnostic.query.filter_by(pid=patient.id).all()
        testsList = []
        for test in tests:
            testsList.append(
                Diagnosistests.query.filter_by(test_id=test.dtest_id).all())
        print(testsList)
        allPatients = Patient.query.all()
        return render_template('diagnostic/searchPatientDiagnostic.html',
                               patient=patient,
                               diagnosis=zip(tests, testsList),
                               patients=allPatients)

        return redirect('/diagnostic_dashboard')
Exemple #14
0
def delete_post(post_id):
	post = Post.query.get_or_404(post_id)
	if post.author != current_user:
		abort(403)
	# How to execute the delete command???
	flash('Post has been deleted!', 'info')
	return redirect(url_for('home'))
Exemple #15
0
def edit(OrmForm, model):
    form = OrmForm(request.form, model)
    if form.validate_on_submit():
        form.populate_obj(model)
        model.put()
        flash("MyModel updated")
        return redirect(url_for("index"))
    return render_template("editor.html", form=form)
Exemple #16
0
def admin_panel():
    if 'admin' in session:
        return render_template("panels/admin/homepage.html",
                               events=sort_events(EventsModel.query.all()))
    else:
        flash("Admin Not Logged In", 'danger')
        print("Admin Not Logged In")
        return redirect('/login')
Exemple #17
0
def new_post():
	form =PostForm()
	if form.validate() and request.method == 'POST':
		post = Post(title=form.content.data, content=form.content.data, author=current_user)
		post.save()
		flash('New post created', 'success')
		return redirect(url_for('users.index'))
	return render_template('create_post.html', title='New Post', form=form, legend='New Post')
Exemple #18
0
def display_events():
    if 'user' in session or 'admin' in session:  # accessible only if user or admin is logged in
        return render_template("events/homepage.html",
                               events=sort_events(EventsModel.query.all()))
    else:
        flash("Not Logged In", 'danger')
        print("Not Logged In")
        return redirect('/login')
Exemple #19
0
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    send_email(current_user.email,
               "Confirm Your Account",
               'auth/email/confirm',
               user=current_user,
               token=token)
    flash(_("A confirmation email has been sent to you by email."), "s")
    return redirect(request.args.get('next') or url_for('main.index'))
Exemple #20
0
 def wrap(*args, **kwargs):
     if 'logged_in' in session:
         return f(*args, **kwargs)
     else:
         message = Markup(
             "<a href='/login'>Sign in</a> or <a href='/register'>register</a> to play."
         )
         flash(message)
         return f(*args, **kwargs)
Exemple #21
0
def get_new_username():

    if request.method == 'POST':
        username_new = request.form['get-user']
        password = request.form['password']
        verify = request.form['verify']

        existing_user = User.query.filter_by(username=username_new).first()

        username_error = ""
        password_error = ""
        verify_error = ""

        if not username_new:
            username_error += "Must enter a User Name, Cannot be Blank. "
        else:
            if len(username_new) > 20 or len(username_new) < 3:
                username_error += "User Name must be at least 3 characters and no more than 20 characters long. "
            if " " in username_new:
                username_error += "User Name must not have any spaces. "
            if existing_user:
                username_error += "User already exists."

        if not password:
            password_error += "Must enter a Password, Cannot be Blank. "
        else:
            if len(password) > 20 or len(password) < 3:
                password_error += "Password must be at least 3 characters and no more than 20 characters long. "
            if " " in password:
                password_error += "Password must not have any spaces. "

        if not verify:
            verify_error += "Must enter Verify Password, Cannot be Blank. "
        else:
            if len(verify) > 20 or len(verify) < 3:
                verify_error += "Verify Password must be at least 3 characters and no more than 20 characters long. "
            if " " in verify:
                verify_error += "Verify Password must not have any spaces. "

        if verify not in password:
            password_error += "Password and Verify Password do not match. "

        if any(username_error) or any(password_error) or any(verify_error):
            return render_template('signup.html',
                                   username=username_new,
                                   username_error=username_error,
                                   pswd_error=password_error,
                                   verify_error=verify_error)
        else:
            new_user = User(username_new, password)
            db.session.add(new_user)
            db.session.commit()
            session['username'] = username_new
            flash_string = "New user: "******" was sucessfully created!"
            flash(flash_string)
            return redirect('/')
Exemple #22
0
def delete(id):
    patient = Patient.query.get_or_404(id)
    histories = History.query.filter_by(hid=id).all()
    for history in histories:
        db.session.delete(history)
    db.session.commit()
    db.session.delete(patient)
    db.session.commit()
    flash('Patient deleted!', 'success')
    return redirect('/patients')
Exemple #23
0
def index():
    if request.method == 'POST':
        if not request.form['email'] or not request.form['password']:
            flash('Please enter all the fields', 'error')
        else:
            if str(request.form['email']) == str('admin') and str(
                    request.form['password']) == str('admin'):
                return redirect(url_for('show_users'))

    return render_template('index.html')
Exemple #24
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = Users.query.filter_by(id=form.id.data).first()
        login_user(user, remember=True)
        flash('Вы вошли как {}'.format(user.name), 'success')
        return redirect(url_for('home'))
    return render_template('login.html', form=form)
Exemple #25
0
	def position_view(positionId):
		if len(Position.query.filter(Position.id == positionId).filter(Position.available == True).all()) == 0:
			flash('This position is not available.', 'danger')
			return render_template('template.html'), 404

		position = Position.query.filter(Position.id == positionId).filter(Position.available == True)[0]
		if position.company_id == session['company_id']:
			return render_template('company/position.html', position=position)
		else:
			return render_template('students/position.html', position=position)
Exemple #26
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email_or_username.data).first()
        if user is None:
            user = User.query.filter_by(username=form.email_or_username.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            return redirect(request.args.get("next") or url_for("main.index"))
        flash(_("Invalid user name or password"), "d")
    return render_template("auth/login.html", form=form)
Exemple #27
0
def confirm(token):
    if current_user.confirmed:
        return redirect(url_for('main.index'))
    if current_user.confirm(token):
        flash(_("You have confirmed your account. Thanks!"), 's')
    else:
        flash(
            _("The confirmation link is invalid or has expired." +
              "click <a href='{{url_for('auth.resend_confirmation'}}'>" +
              "here</a>" + "to resend the link"), 'd')
    return redirect(url_for('main.index'))
Exemple #28
0
def pharmacistinfo():
    if (current_user.role != 'pharm'):
        return render_template('auth/accessDenied.html')
    if request.method == 'POST':
        search_ssnId = request.form['ssnId']
        try:
            searched_ssnId = int(search_ssnId)
        except:
            flash("Please Enter a valid Integer Id!" , "danger")
            return redirect('/pharmacist_dashboard')
        return redirect(url_for('patientmedinfo',ssn=searched_ssnId))
    def position_view(positionId):
        if len(
                Position.query.filter(Position.id == positionId).filter(
                    Position.available == True).all()) == 0:
            flash('This position is not available.', 'danger')
            return render_template('template.html'), 404

        return render_template(
            'students/position.html',
            position=Position.query.filter(Position.id == positionId).filter(
                Position.available == True)[0])
Exemple #30
0
def reactivate(id):
    if (current_user.role != 'desk'):
        return render_template('auth/accessDenied.html')

    patient = Patient.query.get_or_404(id)
    patient.admissionDate = str(datetime.now())[:10]
    patient.status = "Active"
    db.session.commit()

    flash('Patient status activated!', 'success')
    return redirect('/patients')
Exemple #31
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email_or_username.data).first()
        if user is None:
            user = User.query.filter_by(
                username=form.email_or_username.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            return redirect(request.args.get('next') or url_for('main.index'))
        flash(_('Invalid user name or password'), 'd')
    return render_template('auth/login.html', form=form)
Exemple #32
0
def updatemedlist(ssn):
    if (current_user.role != 'pharm'):
        return render_template('auth/accessDenied.html')
    for med in newMed:
        quantity_med = Med.query.get(med['medId'])
        quantity_med.quantity = int(quantity_med.quantity)-int(med['quant'])
        db.session.commit()
        obj = Pmed(pid=med['pid'],medicineId=med['medId'],quant=med['quant'],amount=med['amount'])
        db.session.add(obj)
        db.session.commit()
    newMed.clear()
    flash('Medicines Issued Succesfully !',"success")
    return redirect(url_for('patientmedinfo',ssn=ssn))
Exemple #33
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        user = User(email=form.email.data, username=form.username.data, password=form.password.data)
        profile = User_Profile(id=user.id)
        db.session.add(user)
        db.session.add(profile)
        db.session.commit()
        token = user.generate_confirmation_token()
        send_email(user.email, "Confirm Your Account", "auth/email/confirm", user=user, token=token)
        flash(_("A confirmation email has been sent to you by email."), "s")
        return redirect(url_for("auth.login"))
    return render_template("auth/register.html", form=form)
Exemple #34
0
 def offer_details(id):
     try:
         return render_template(
             'core/' + str(session['language'] or get_locale()) +
             '/visitor/offer-details.html',
             recents=Position.query.filter(
                 Position.available == True).order_by(
                     Position.id.desc()).limit(5).all(),
             offer=Position.query.filter(Position.available == True).filter(
                 Position.id == id).one())
     except:
         flash('This offer was not found.', "warn")
         return render_template("404.html"), 404
Exemple #35
0
def add_olympiad():
    title = "Добавление олимпиады"
    form = EditorOlympiad()

    if form.validate_on_submit():
        new_olympiad = Olympiad(name=form.name.data,
                                max_balls=form.max_balls.data,
                                description=form.description.data)
        db.session.add(new_olympiad)
        db.session.commit()
        flash('Добавлена Олимпиада!')
        return redirect(url_for("hierarchy"))

    flash(flash_editor_errors(form))
    return render_template("editor.html", form=form, action='/add/olympiad', title=title)
Exemple #36
0
def confirm(token):
    if current_user.confirmed:
        return redirect(url_for("main.index"))
    if current_user.confirm(token):
        flash(_("You have confirmed your account. Thanks!"), "s")
    else:
        flash(
            _(
                "The confirmation link is invalid or has expired."
                + "click <a href='{{url_for('auth.resend_confirmation'}}'>"
                + "here</a>"
                + "to resend the link"
            ),
            "d",
        )
    return redirect(url_for("main.index"))
Exemple #37
0
def server_start():
    p = OptionParser()
    p.add_option('-d', action = "store_true",
                 dest = 'daemonize', help = "Run the server as a daemon")
    p.add_option('-q', '--quiet', action = "store_true",
                 dest = 'quiet', help = "Don't log to console")
    p.add_option('-p', '--pidfile',
                 dest = 'pidfile', default = None,
                 help = "Store the process id in the given file")

    options, args = p.parse_args()

    config = os.path.join(rundir, 'config.ini')

    # Config app
    ca = configApp(config)
    initDb()

    # Start threads
    myCrons = CronJobs(cherrypy.engine, ca, debug)
    myCrons.subscribe()

    # Update script
    myUpdater = Updater(cherrypy.engine)
    myUpdater.subscribe()

    # User config, use own stuff to prevent unexpected results
    cherrypy.config.update({
        'global': {
            'server.thread_pool':               10,
            'server.socket_port':           int(ca.get('global', 'port')),
            'server.socket_host':               ca.get('global', 'host'),
            'server.environment':               ca.get('global', 'server.environment'),
            'engine.autoreload_on':             ca.get('global', 'engine.autoreload_on') and not options.daemonize,
            'tools.mako.collection_size':       500,
            'tools.mako.directories':           os.path.join(path_base, 'app', 'views'),

            'basePath':                         path_base,
            'runPath':                          rundir,
            'cachePath':                        cachedir,
            'debug':                            debug,
            'frozen':                           frozen,

            # Global workers
            'config':                           ca,
            'updater':                          myUpdater,
            'cron':                             myCrons.threads,
            'searchers':                        myCrons.searchers,
            'flash':                            app.flash()
        }
    })

    # Static config
    conf = {
        '/': {
            'request.dispatch': Routes(),
            'tools.sessions.on':  True,
            'tools.sessions.timeout': 240,

            'tools.gzip.on': True,
            'tools.gzip.mime_types': ['text/html', 'text/plain', 'text/css', 'text/javascript', 'application/javascript']
        },
        '/media':{
            'tools.staticdir.on': True,
            'tools.staticdir.root': path_base,
            'tools.staticdir.dir': "media",
            'tools.expires.on': True,
            'tools.expires.secs': 3600 * 24 * 7
        },
        '/cache':{
            'tools.staticdir.on': True,
            'tools.staticdir.root': rundir,
            'tools.staticdir.dir': "cache",
            'tools.expires.on': True,
            'tools.expires.secs': 3600 * 24 * 7
        }
    }

    # Don't use auth when password is empty
    if ca.get('global', 'password') != '':
        conf['/'].update({
            'tools.basic_auth.on': True,
            'tools.basic_auth.realm': 'Awesomeness',
            'tools.basic_auth.users': {ca.get('global', 'username'):ca.get('global', 'password')},
            'tools.basic_auth.encrypt': app.clearAuthText
        })
        cherrypy.tools.mybasic_auth = cherrypy.Tool('on_start_resource', app.basicAuth)

    # I'll do my own logging, thanks!
    cherrypy.log.error_log.propagate = False
    cherrypy.log.access_log.propagate = False

    #No Root controller as we provided all our own.
    cherrypy.tree.mount(root = None, config = conf)

    # Stop logging
    if options.quiet:
        cherrypy.config.update({'log.screen': False})

    # Deamonize
    if options.daemonize:
        cherrypy.config.update({'log.screen': False})
        plugins.Daemonizer(cherrypy.engine).subscribe()

    # PIDfile
    if options.pidfile:
        plugins.PIDFile(cherrypy.engine, options.pidfile).subscribe()

    # Setup the signal handler
    if hasattr(cherrypy.engine, "signal_handler"):
        cherrypy.engine.signal_handler.subscribe()
    if hasattr(cherrypy.engine, "console_control_handler"):
        cherrypy.engine.console_control_handler.subscribe()


    ## start the app
    try:
        cherrypy.engine.start()
    except:
        sys.exit(1)
    else:

        # Launch browser
        if ca.get('global', 'launchbrowser'):
            app.launchBrowser(ca.get('global', 'host'), ca.get('global', 'port'))

        cherrypy.engine.block()
Exemple #38
0
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    send_email(current_user.email, "Confirm Your Account", "auth/email/confirm", user=current_user, token=token)
    flash(_("A confirmation email has been sent to you by email."), "s")
    return redirect(request.args.get("next") or url_for("main.index"))
Exemple #39
0
def logout():
    logout_user()
    flash("You have been logged out.", "s")
    return redirect(request.args.get("next") or url_for("main.index"))