Serving HTML/CSS/JS with Rocket - html

I am attempting to use the Rust Rocket framework to serve as my backend for hosting my website, but I am struggling to serve basic HTML files and their associated files.
As far as things go, this is the code for my "website". I really am unsure how to do this, and as a novice to backend development, I figured I would see if there was an answer here.
#[macro_use] extern crate rocket;
use std::fs::File;
use rocket::{response::{Redirect}, fs::FileServer};
#[get("/")]
fn index() -> Redirect {
let redirect = Redirect::to(uri!("/home"));
redirect
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
I am unsure what the best way to structure my front-end files. Any advice/help is appreciated. Please go easy on me, as I am a inexperienced when it comes to backend development.
I have tried the static examples listed on the GitHub, however, I think run into issues where I can view the HTML page but images, CSS, and JavaScript files are not served properly.

Here is the code that ended up working best for me. I would like to break this down for anyone who may be struggling to get into backend web development, especially for rust.
#[macro_use] extern crate rocket;
use rocket::{fs::NamedFile, response::Redirect};
use std::path::{Path, PathBuf};
#[get("/")]
fn index() -> Redirect {
let redirect = Redirect::to(uri!("/home"));
redirect
}
#[get("/home")]
async fn home () -> Option<NamedFile> {
NamedFile::open("client/index.html").await.ok()
}
#[get("/<file..>")]
async fn files(file: PathBuf) -> Option<NamedFile> {
NamedFile::open(Path::new("client").join(file)).await.ok()
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index, home, files])
}
I will start with the first section.
#[macro_use] extern crate rocket;
use rocket::{fs::NamedFile, response::Redirect};
use std::path::{Path, PathBuf};
^ This is just our declarations of what I needed to use.
#[get("/")]
fn index() -> Redirect {
let redirect = Redirect::to(uri!("/home"));
redirect
}
#[get("/home")]
async fn home () -> Option<NamedFile> {
NamedFile::open("client/index.html").await.ok()
}
^ This section is for redirecting the blank, index URL to not give a 404, and to go to a URL with "/home" at the end. This is just for my personal preference, but now you know how to do it too!
In the end, I determined by looking at the Rust analyzer examples for NamedFile, how to specifically open different files.
#[get("/<file..>")]
async fn files(file: PathBuf) -> Option<NamedFile> {
NamedFile::open(Path::new("client").join(file)).await.ok()
}
^ This section is to handle other files, such as CSS and JavaScript linked in HTML documents. I imagine this is not a very secure method, but for a portfolio website, I don't need very robust security.
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index, home, files])
}
^ Finally, you just end up mounting the routes. Doing it this way seemed to work for me. I'm sure someone smarter with more experience can explain it in a more elegant way than I have, but if you're in a pinch like me and you're at your wit's end, hopefully, this is a much-needed life preserver when you are drowning.

Related

Inject HTML signature into Gmail from hosted page

I have the basic shell of a Chrome extension done and have come to the point where I am trying to inject an HTML signature into Gmail using code hosted on an unindexed page on my site. The reason I want to do this is to be able to include web fonts, something that for the life me I can't figure out why Gmail hasn't allowed you to do from their font library.
In any regard, as I said, I have a right-click context menu option ready to trigger a script from my js function page and the extension loads without errors. I need to figure out the best way to inject the HTML into the email and without losing any of the formatting that has been done on the page.
I have created the extension manifest, set the permissions on the context menu and created a function to call back to the js page that will inject the signature.
var contextMenus = {};
contextMenus.createSignature =
chrome.contextMenus.create(
{"title": "Inject Signature",
"contexts": ["editable"]},
function (){
if(chrome.runtime.lastError){
console.error(chrome.runtime.lastError.message);
}
}
);
chrome.contextMenus.onClicked.addListener(contextMenuHandler);
function contextMenuHandler(info, tab){
if(info.menuItemId===contextMenus.createSignature){
chrome.tabs.executeScript({
file: 'js/signature.js'
});
}
}
The end result is nothing enters the page and get massive errors related to cross-site because the domain is not the same obviously. This has obviously been solved as there are numerous signature extensions out there. I would probably use one of theirs but a) I want to build it on my own, b) they all want you to use their templates, none of them that I have seen will let you just use your own code.
So, any ideas?

Organizing code in HTML

So I'm self studying HTML and I was wondering if there's a way to organize my code in a better way, like when you use pragma region and pragma endregion in C++.
I'm really looking for something to be as simple as that, to be 2 or maybe 3 code lines at best.
For those who doesn't know C++, pragma is used like this:
#pragma region NameOfMyRegion
// Code....
#pragma endregion
And then you can just expand and collapse it as you wish, and the name of the region will be what is displayed instead of the whole bunch of code section in the region. The example is in this link: http://pho.to/9Z7LB
Looking for something as super simple, because I only know C++ and just started HTML.
That doesn't exist in pure html but it does in javascript (which can be embedded in a script tag). Javascript can be used to inject HTML into your page so through this method people often embed HTML indirectly via imported javascript.
In ES6 one of the newer versions of Javascript you can use 'import':
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
Example would point to a file called example.js which would export its functions using a model like.
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
Example from: http://www.2ality.com/2014/09/es6-modules-final.html
Because ES6 isn't universally used by all browsers many people use a pre-compiler which compiles modern ES6 javascript code into an older version of javascript. A common tool for this is Babel.

Swift parser.parse() returns false, but no parserError

I'm trying to create an iOS app that reads the RSS feed from a website (in my case http://www.quest.nl/rss), parses the RSS to a UITableView, from which the user can select an article. The selected article is then presented in an UIWebView. I can successfully parse the XML, but when I try to parse the article link (article link is html, but I figured i might as well use NSXMLParser too) I run into problems. parser?.parse() returns false (meaning something went wrong), but the contents of parser?.parserError are still nil.
My code:
#objc protocol HTMLParserDelegate{
func parsingWasFinished()
}
import UIKit
class HTMLParser: NSObject, NSXMLParserDelegate {
func startParsingWithContentsOfURL(linkURL: NSURL) {
let parser = NSXMLParser(contentsOfURL: linkURL)
parser?.delegate = self
println(parser?.parse())
}
func parser(parser: NSXMLParser!, parseErrorOccured parseError: NSError!) {
println(parseError.description)
}
func parser(parser: NSXMLParser,
validationErrorOccured validationError: NSError!) {
println(validationError.description)
}
func parserDidEndDocument(parser: NSXMLParser!) {
//println("finished! :D")
delegate?.parsingWasFinished()
}
}
I have tried deleting all methods I implemented for the parser (see above), but even that didn't solve the parsing.
Using a url for testing (http://www.quest.nl/foto/de-5-gekste-dieren-van-2014), I noticed that the parser gets to line 80, but doesn't get to the on line 95, while successfully parsing all previous tags.
Thanks to the comment by Rob I got to take a look at Hpple, which solved my problems.
For anyone looking for an answer on my question, I'll shortly detail my steps.
Indeed, HTML is not equal to XML, and even though the HTML I used was formatted quite nicely, XML Parsers had huge problems with dealing with the code. Then I turned to Hpple, which is extremely nice and user friendly, and used code I found at Github, which I added to my project, and from that point on, I could use Hpple and the nice, easy to use, syntax to parse the HTML, without any problems.
Thanks everyone for the tips!

How to handle a multi-site environment

If I have an application in WebPages, I would like to know how to enable multi-site capabilities? I understand the _SiteLayout.cshtml file or what not can handle the template for one site, but how about if I wanted to change that for a different site? The different site would be passed to the application by ServerVariable (domain name), so I'm assuming there would need to be some type of controller in place to handle this? But WebPages doesn't have controllers and I'm not learning MVC now. What would be my options at this point? Thank you.
You could check the requested domain and then select the layout page, like this:
#{
if (Request.Url.Host == "domain1.com")
{
Layout = "/Shared/_Layout1.cshtml";
}
else if (Request.Url.Host == "domain2.com")
{
Layout = "/Shared/_Layout2.cshtml";
}
else
{
Layout = "/Shared/_Layout.cshtml";
}
}

How to hide HTML and other Content in EJS and Node

Having a tough time doing a simple web site in EJS.
I have this set up in my server file:
//Use the .html extension instead of having to name the views as *.ejs
server.engine('.html', require('ejs').__express);
// This avoids having to provide the extension to res.render()
server.set('view engine', 'html');
//set up directory to serve css and javascript files
server.use(Express.static(__dirname, '/views'));
This works great. I have HTML files, I have graphics, I have CSS. I am serving it up with a simple controller that renders the page. Nothing dynamic in these pages. But I do want them protected with an id/password system, and only served up through Express.
The access works fine, I have an end point set up to serve them. I'm forcing log in in that end point. But the problem is, that if someone knows the actual path to those files, they can get at them. So, the access is localhost:8081/admin/documentation/. However, the files are at /views/app_documents. And by entering in localhost:8081/views/app_documents/file_name.html, they can download/view the content, without going through my controls. I moved the content out of views, and grab it in my code, and serve it up, but that doesn't work for images or CSS.
Any suggestions for how to get around this?
Well, the things you find out after the fact.
This:
server.use(Express.static(__dirname, '/views'));
Is very bad. It should be:
server.use(Express.static('./views'));
The way it was, you could download our code, also. So, server.js was available for download. Yikes.
Live and learn.
Still can download the content without going through my authentication, though.
In case anyone else wants to do this, took a while. There are a few problems, as you still need to be able to directly access JS libraries, images and CSS. I found my answer in enter link description here.
The following modifications to that code does the trick. UserIsAllowed checks my permissions system to see if they can access that folder. If they can, no harm, off you go. Otherwise, kill the attempt. They get ACCESS_DENIED back as a string. I can't just kill anyone not going through my code, because then the CSS and images would not work. But this functions nicely. I now am able to serve up content based on my custom permissions system, which is part of a bunch of other administration functions. I can also have multiple different areas based on the URL that are protected by different privileges.
// This function returns a middleware function. It checks to see if the user has access
var protectPath = function(regex)
{
return function(request, response, next)
{
if (!regex.test(request.url)) { return next(); }
userIsAllowed(regex,function(allowed)
{
if (allowed)
{
next(); // send the request to the next handler, which is express.static
}
else
{
response.end('ACCESS_DENIED');
}
});
function userIsAllowed(regex,callback) {
if (regex.test('documentation_website') && request.session.admin_me && _.contains(request.session.admin_me["privileges"],"view_server_documentation")) callback(true);
else callback(false);
}
};
};
server.use(protectPath(/^\/documentation_website\/.*$/));