Exemplo n.º 1
0
def userpage():
	
	users = File.query.order_by(File.id)
	if users != None:
		return render_template('users.html', users=(users))
	else:
		return render_template('secret.html', input_var='Brugen findes ikke').encode( "utf-8" )
Exemplo n.º 2
0
def index():


	'''
		Hvis brugeren er logget ind, hvis forside
		Ellers hvis "spalshpage", hvor man kan oprette bruger og logge ind

	'''
	if g.userIsloggedIn == True:
		return render_template('pages/forside.jinja')
	else: 
		return render_template('pages/splashpage.jinja')
Exemplo n.º 3
0
def login():
	

	'''
		Her skal kommentaren stå :)


	'''



	
	if 'next' in request.args:
		returnURL = request.args['next']
	else:
		returnURL = url_for('index')


	if request.method == 'POST' and g.userIsloggedIn == False:
		loggedIn = tryLogin(request.form['username'], request.form['password'], request.form['KeepMeLoggedIn'], request.form['authenticity_token'])
		
		if loggedIn[2] != '':
			flash(loggedIn[1], loggedIn[2])
		else:
			flash(loggedIn[1])


		if loggedIn[0] == False: 

			serverAuthenticationCode = bcrypt.generate_password_hash(app.config['SECRET_KEY'], 2)
			return render_template('login.html', formerUsernameInput=request.form['username'], setAuthenticationCode=serverAuthenticationCode)

		return redirect(returnURL)

	else:
		if 'next' in request.args and g.userIsloggedIn:
			return redirect(request.args['next'])

		elif g.userIsloggedIn:
			flash('Du er allrede logget ind som {}'.format(g.user),'info')
			return redirect(returnURL)

		else:
			serverAuthenticationCode = bcrypt.generate_password_hash(app.config['SECRET_KEY'], 2)
			return render_template('login.html', setAuthenticationCode=serverAuthenticationCode)
Exemplo n.º 4
0
def uploadFile():

    if request.method == 'POST':
        file = request.files['file']
        if file:
            fileId = tryCreateFile(file.filename, file.read())
            return fileId
    else:
        return render_template('upload.html')
Exemplo n.º 5
0
def index():
    print(session)
    try:
        if session['activeUser']:
            return redirect(url_for('login'))
    except KeyError:
        redirect('before_first_request')

    return render_template('main/home.html')
Exemplo n.º 6
0
def get_all_documents_from_user(userId):

	'''
		Hent de 20 nyeste dokumneter lavet af nuværedene bruger
		og lav en liste der tilgenlig for ikke in-loggede bruger

	'''

	documents = Document.query.filter_by(user_id=userId).order_by(Document.created.desc()).limit(20)
	user = User.query.filter_by(id=userId).first()
	return render_template('pages/displayDocumentsNotLoggedIn.jinja', theDocuments=documents, theUser=user)
Exemplo n.º 7
0
def createUser():

	'''
		Her skal kommentaren stå :)


	'''


	serverAuthenticationCode = bcrypt.generate_password_hash(app.config['SECRET_KEY'], 2)
	returnURL = url_for('index')


	if (request.method == 'POST') and request.form['fromFrontPage'] == 'true' and g.userIsloggedIn == False:
		serverAuthenticationCode = bcrypt.generate_password_hash(app.config['SECRET_KEY'], 2)
		return render_template('createuser.html',formerUsernameInput=request.form['username'], formerPasswordInput=request.form['userPassword'], setAuthenticationCode=serverAuthenticationCode)


	elif (request.method == 'POST') and g.userIsloggedIn == False:
		theUser = tryCreateUser(request.form['username'], request.form['userPassword'], request.form['KeepMeLoggedIn'], request.form['authenticity_token'])

		if theUser[2] != '':
			flash(theUser[1], theUser[2])
		else:
			flash(theUser[1])

		if theUser[0] == False: 
			serverAuthenticationCode = bcrypt.generate_password_hash(app.config['SECRET_KEY'], 2)
			return render_template('createuser.html',formerUsernameInput=request.form['username'], setAuthenticationCode=serverAuthenticationCode)
		return redirect(returnURL)
	
	else:

		if g.user != None:
			flash('Du er allrede logget ind som {}'.format(g.user),'info')
			return redirect(url_for('index'))
			
		else:
			serverAuthenticationCode = bcrypt.generate_password_hash(app.config['SECRET_KEY'], 2)
			return render_template('createuser.html', setAuthenticationCode=serverAuthenticationCode)
Exemplo n.º 8
0
def login():
    sessionKeys = session.keys()

    if 'activeUser' in sessionKeys and 'username' in sessionKeys and 'currentUsernameReceiver' in sessionKeys:
        if session['activeUser']:
            return render_template('logged/chat.html')
    else:
        redirect('before_first_request')

    # GET
    if request.method == "GET":
        return redirect(url_for('index'))

    # POST
    if request.method == 'POST':
        username = request.form['username']
        if username == '':
            flash("You must enter your username to login", 'danger')
            return redirect(url_for('index'))

        # try:
        #     if username != session['username']:
        #         userFound = chat.searchUser(session['username'])
        #         if users[i] == session['username']:
        #             chat.deleteUser()
        # except KeyError:
        #     print('error')
        #     redirect('before_first_request')

        if not users.searchUserByUsername(username):
            users.appendUser(username)
        chatCreated = users.appendChat([username, username])

        chatCreated.submitMessage(username, username, "Hola")
        chatCreated.submitMessage(username, username, "Buenas")

        session['username'] = username
        session['activeUser'] = True
        session['currentUsernameReceiver'] = username
        return render_template('logged/chat.html')
Exemplo n.º 9
0
def create_service():
    if request.method == "GET":
        return render_template("create_service.html")

    elif request.method == "POST":

        title = request.form.get("title")
        image = request.files.get("photo")
        description = request.form.get("description")
        price = request.form.get("price")

        try:

            session = sessions["main_database"]

            user_id = cookie["id"]

            image = Images(
                id=max([elem.id for elem in session.query(Images).all()]) + 1,
                out_id=max(
                    [elem.out_id for elem in session.query(Images).all()]) + 1,
                image=bytes(image.read()))
            description = Description(
                id=max([elem.id
                        for elem in session.query(Description).all()]) + 1,
                description=description,
                images_id=image.out_id)
            service = Service(user_id=user_id,
                              name=title,
                              description_id=description.id,
                              price=price)

            session.add(image)
            session.add(description)
            session.add(service)

            session.commit()

        except Exception:
            return redirect('/')

        return redirect('/')
Exemplo n.º 10
0
def update_document(fileId):

	'''	
		(GET) 	Vis Opdaterings side, hvis nuværedene bruger ejer dokumentet  
		(POST)	Updater dokument fra input 

	'''


	if request.method == 'POST':
		
		return update_document_from_dict(fileId, request.form, request.files['file'])

	else:
		file = Document.query.filter_by(id=fileId).first()

		if file.user_id == int(g.userId):
			return render_template('pages/updateDocument.jinja', theDocument=file)
		else:
			abort(403)
Exemplo n.º 11
0
def html_view(fileId):

	'''
		Hvis html udgave af dokumentet
		samt opdater statestik for produkt (dokument/html)
	'''

	if Document.query.filter_by(id=fileId).first() != None:

		HTML = create_HTML_from_id(fileId)
		document = Document.query.filter_by(id=fileId).first()
		user = User.query.filter_by(id=document.user_id).first()

		html_id = Product.query.filter_by(document_id=fileId, type='html').first().id
		update_or_create_Statistic(html_id, 'displays')
		
		return render_template('pages/documentWebsiteView.jinja', theDocument=document, theUser=user, content=HTML[0])

	else:
		abort(404)
Exemplo n.º 12
0
def searchWithParam():


	'''

		Søg efter dokument ud fra meta data
		maksimal 20 svar

		og retuner side med svar

	'''
	
	requestString = request.args.get('search_input')
	parameters = requestString.split(" ",1)
	orParam = ''


 	search = ''
	for i in range(len(parameters)):
		if i == 0:
			SearchResult = Document.query.filter(db.or_(Document.name.ilike('%'+parameters[i]+'%'),
									Document.subtitle.ilike('%'+parameters[i]+'%'),
									Document.description.ilike('%'+parameters[i]+'%'),
									Document.subject.ilike('%'+parameters[i]+'%'),
									Document.topic.ilike('%'+parameters[i]+'%'),
									Document.education_level.ilike('%'+parameters[i]+'%'))).order_by(Document.created.desc())
		else:

			newSearchResult = SearchResult.from_self().filter(db.or_(Document.name.ilike('%'+parameters[i]+'%'),
									Document.subtitle.ilike('%'+parameters[i]+'%'),
									Document.description.ilike('%'+parameters[i]+'%'),
									Document.subject.ilike('%'+parameters[i]+'%'),
									Document.topic.ilike('%'+parameters[i]+'%'),
									Document.education_level.ilike('%'+parameters[i]+'%'))).limit(20)
			
			if newSearchResult.all() != []:
				SearchResult = newSearchResult


	return render_template('pages/search.jinja', param=requestString, theDocuments=SearchResult, amount=SearchResult.count())
Exemplo n.º 13
0
def create_comment(service_id: int):
    if request.method == "GET":
        return render_template("create_comment.html")

    elif request.method == "POST":

        impression = request.form.get("impression")
        pluses = request.form.get("pluses")
        minuses = request.form.get("minuses")
        comment = request.form.get("comment")
        rating = request.form.get("rating")

        try:
            session = sessions["main_database"]

            user_id = cookie["id"]

            description = Description(
                id=max([elem.id
                        for elem in session.query(Description).all()]) + 1,
                description=delimiter.join(
                    (impression, pluses, minuses, comment)))
            comment = Comment(
                id=max([elem.id
                        for elem in session.query(Description).all()]) + 1,
                user_id=user_id,
                service_id=service_id,
                description_id=description.id,
                rating=rating)

            session.add(description)
            session.add(comment)

            session.commit()

        except Exception as e:
            return redirect('/')

        return redirect('/')
Exemplo n.º 14
0
def registration():
    """Website registration page"""

    if request.method == "GET":
        return render_template("registration.html")

    elif request.method == "POST":
        phone = request.form.get("phone")
        name = " ".join(
            [request.form.get("surname"),
             request.form.get("name")])
        password = request.form.get("password")
        image = request.files["file"]

        try:
            session = sessions["main_database"]

            image = Images(
                id=max([elem.id for elem in session.query(Images).all()]) + 1,
                out_id=max(
                    [elem.out_id for elem in session.query(Images).all()]) + 1,
                image=bytes(image.read()))
            user = User(phone=phone,
                        password=password,
                        name=name,
                        image_id=image.out_id)
            user_id = user.id

            session.add(image)
            session.add(user)
            session.commit()
        except Exception:
            return redirect('/registration')

        cookie["id"] = user_id

        return redirect('/')
Exemplo n.º 15
0
def denHemmligeSide():
    return render_template('secret.html', input_var=session)
Exemplo n.º 16
0
def cookies():
    #cookie login remeber me -
    return render_template('cookies.html')
def page_not_found(error):
	return render_template('index.html', input_var=error)
Exemplo n.º 18
0
def render_login_user(message=None):
	if message != None:
		flash(message, 'error')
	
	return render_template('pages/login.jinja')
Exemplo n.º 19
0
def render_create_user(message=None):
	if message != None:
		flash(message, 'error')

	return render_template('blocks/createUser.jinja')
Exemplo n.º 20
0
def profile(user_id: int, type: str = "services"):
    if request.method == "POST" and request.form.get(
            "tel") and request.form.get("password"):
        user = sessions["main_database"].query(User) \
            .filter(User.phone == request.form.get("tel"), User.password == request.form.get("password")).first()
        if user:
            cookie["id"] = user.id
            return redirect(f'/profile/{user.id}')

    session = sessions["main_database"]

    searched = request.form.get("search_label")
    if searched:
        return redirect('/')

    user = session.query(User).filter(User.id == user_id).first()
    user_image = session.query(Images).filter(
        Images.out_id == user.image_id).first()

    services = session.query(Service).filter(Service.user_id == user_id).all()

    data = {
        "registered": cookie.get("id") == user_id,
        "user": {
            "id": user_id,
            "name": user.name,
            "image":
            str(buffer_image(user_image.id, user_image.image)) + ".png",
            "phone": user.phone,
            "average_rating": 0
        },
        "services": [],
        "comments": []
    }

    for service in services:
        description = session.query(Description).filter(
            Description.id == service.description_id).first()
        images = session.query(Images).filter(
            Images.out_id == description.images_id).all()

        service_comments = session.query(Comment, Description) \
            .filter((Comment.service_id == service.id), (Description.id == Comment.description_id)).all()

        data["services"].append({
            "id": service.id,
            "name": service.name,
            "price": service.price,
            "description": {
                "images": [
                    str(buffer_image(image.id, image.image)) + ".png"
                    for image in images
                ],
                "description": {
                    "comment": description.description
                },
            },
        })

        for comment, description in service_comments:
            author = session.query(User).filter(
                User.id == comment.user_id).first()
            author_image = session.query(Images).filter(
                Images.out_id == author.image_id).first()
            data["comments"].append({
                "id": comment.id,
                "author": {
                    "id":
                    author.id,
                    "name":
                    author.name,
                    "image":
                    str(buffer_image(author_image.id, author_image.image)) +
                    ".png"
                },
                "description": {
                    "images": [
                        str(buffer_image(image.id, image.image)) + ".png"
                        for image in session.query(Images).filter(
                            Images.id == description.images_id).all()
                    ],
                    "description": {
                        "impression":
                        description.description.split(delimiter)[0],
                        "pluses": description.description.split(delimiter)[1],
                        "minuses": description.description.split(delimiter)[2],
                        "comment": description.description.split(delimiter)[3]
                    }
                },
                "rating": comment.rating
            })
            data["user"]["average_rating"] += comment.rating

    try:
        data["user"]["average_rating"] /= len(data["comments"])
    except ZeroDivisionError:
        data["user"]["average_rating"] = 5

    if type == "services":
        return render_template("profile.html", data=data, len=len, round=round)
    elif type == "create_service":
        return redirect('/create_service')
    elif type == "comment":
        return render_template("profile_comment.html",
                               data=data,
                               len=len,
                               round=round)
    elif type == "rating":
        return render_template("profile_rating.html",
                               data=data,
                               len=len,
                               round=round)
Exemplo n.º 21
0
def base():
    """Website home page"""

    if request.method == "POST" and request.form.get(
            "tel") and request.form.get("password"):
        user = sessions["main_database"].query(User) \
            .filter(User.phone == request.form.get("tel"), User.password == request.form.get("password")).first()
        if user:
            cookie["id"] = user.id
            return redirect(f'/profile/{user.id}')

    global searcher

    session = sessions["main_database"]

    services = session.query(Service).all()

    searched = request.form.get("search_label")
    if searched:
        reload_document(services)

        searcher = ix.searcher()
        query = QueryParser("content", ix.schema).parse(searched)
        search_result = list(searcher.search(query))
        if not search_result:
            services = list(filter(lambda x: searched in x.name, services))
        else:
            services_id = [int(hit["id"]) for hit in search_result]
            services = list(filter(lambda x: x.id in services_id, services))

    data = {"services": []}

    for service in services:
        description = session.query(Description).filter(
            Description.id == service.description_id).first()
        images = session.query(Images).filter(
            Images.out_id == description.images_id).all()

        service_comments = session.query(Comment) \
            .filter((Comment.service_id == service.id)).all()

        data["services"].append({
            "id":
            service.id,
            "name":
            service.name,
            "price":
            service.price,
            "description": {
                "images": [
                    str(buffer_image(image.id, image.image)) + ".png"
                    for image in images
                ],
                "description": {
                    "comment": description.description
                },
            },
            "average_rating":
            sum([comment.rating for comment in service_comments]) /
            (len(service_comments) if len(service_comments) else 1)
        })

    return render_template("base.html", data=data, len=len, round=round)
Exemplo n.º 22
0
def hello_world():
    """ Function Comment """
    return render_template('index.html')
Exemplo n.º 23
0
def index():
    #cookie login remeber me -
    if g.userIsloggedIn:
        return render_template('dashboard.html')
    else:
        return render_template('index.html')
Exemplo n.º 24
0
def service(service_id: int):
    if request.method == "POST" and request.form.get(
            "tel") and request.form.get("password"):
        user = sessions["main_database"].query(User) \
            .filter(User.phone == request.form.get("tel"), User.password == request.form.get("password")).first()
        if user:
            cookie["id"] = user.id
            return redirect(f'/profile/{user.id}')

    session = sessions["main_database"]

    searched = request.form.get("search_label")
    if searched:
        return redirect('/')

    service = session.query(Service) \
        .filter(Service.id == service_id).first()

    service_author = session.query(User) \
        .filter(User.id == service.user_id).first()
    service_author_image = session.query(Images) \
        .filter(Images.out_id == service_author.image_id).first()

    service_description = session.query(Description) \
        .filter(Description.id == service.description_id).first()
    service_description_images = session.query(Images) \
        .filter(Images.out_id == service_description.images_id).all()

    service_comments = session.query(Comment, Description) \
        .filter((Comment.service_id == service.id), (Description.id == Comment.description_id)).all()

    data = {
        "registered": False,
        "service": {
            "author": {
                "id":
                service_author.id,
                "name":
                service_author.name,
                "image":
                str(
                    buffer_image(service_author_image.id,
                                 service_author_image.image)) + ".png",
                "phone":
                service_author.phone,
                "average_rating":
                0
            },
            "id": service.id,
            "name": service.name,
            "price": service.price,
            "description": {
                "images": [
                    str(buffer_image(image.id, image.image)) + ".png"
                    for image in service_description_images
                ],
                "description": {
                    "comment": service_description.description
                },
            },
            "comments": []
        }
    }

    average_rating = 0

    for comment, description in service_comments:
        author = session.query(User).filter(User.id == comment.user_id).first()
        author_image = session.query(Images).filter(
            Images.out_id == author.image_id).first()
        data["service"]["comments"].append({
            "id": comment.id,
            "author": {
                "id":
                author.id,
                "name":
                author.name,
                "image":
                str(buffer_image(author_image.id, author_image.image)) + ".png"
            },
            "description": {
                "images": [
                    str(buffer_image(image.id, image.image)) + ".png"
                    for image in session.query(Images).filter(
                        Images.id == description.images_id).all()
                ],
                "description": {
                    "impression": description.description.split(delimiter)[0],
                    "pluses": description.description.split(delimiter)[1],
                    "minuses": description.description.split(delimiter)[2],
                    "comment": description.description.split(delimiter)[3]
                }
            },
            "rating": comment.rating
        })
        average_rating += comment.rating
    data["service"]["author"]["average_rating"] = average_rating / (len(
        data["service"]["comments"]) if len(data["service"]["comments"]) else
                                                                    1)

    return render_template("service.html", data=data)
def denHemmligeSide():
	return render_template('secret.html', input_var=session)
Exemplo n.º 26
0
def page_not_found(error):
    return render_template('index.html', input_var=error)
def index():
	#cookie login remeber me - 
	if g.userIsloggedIn:
		return render_template('dashboard.html')
	else:
		return render_template('index.html')
def cookies():
	#cookie login remeber me - 
    return render_template('cookies.html')
def index():
    return render_template('index.html')