How to safely use django-ckeditor with Django Rest Framework? - reactjs

I've successfully implemented django-ckeditor with Django REST Framework and React, but I'm pretty sure that the way I've done it is not secure.
I've created an art blog, where each art piece has a rich-text description. Here's a basic example of one of my models with a rich-text field:
from ckeditor.fields import RichTextField
class Artist(models.Model):
biography = RichTextField(blank=True, null=False)
...
So, if saved his biography as "He was a nice guy!", then DRF serializes that as:
<p>He was a <em><strong>nice guy!</strong></em></p>
In my React app, I render it with:
<div dangerouslySetInnerHTML={{__html: artist.biography}} />
But, as the name implies, the React documentation says that this is generally risky.
This is a personal blog, so I'm not worried about other users injecting code into posts. However, I'm sure that someday I'll want to provide a rich-text editor for my users.
Is there a way to implement CKEditor with Django rest framework that doesn't require me to use dangerouslySetInnerHTML? If not, how can I safely implement a rich-text editor, and still use it with DRF?
UPDATE
I've been doing a bit more research, and I've discovered something from Mozilla called Bleach. They describe it this way:
Bleach is an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes.
They go on to say:
Bleach is intended for sanitizing text from untrusted sources. If you find yourself jumping through hoops to allow your site administrators to do lots of things, you're probably outside the use cases. Either trust those users, or don't.
So, in this case, I don't think I need it. Perhaps I'll use it in future projects though.
That still doesn't help me avoid using dangerouslySetInnerHTML, but this is the most practical solution that I can think of.

Related

how to export react JS components to static html

are there any utilities or approaches to export regular react component into an email friendly static html?
for example i have a dashboard using react-table and would love it if there was a way to auto-magically translate that to static html i could insert into an email body.
i can think of a few approaches using a headless browser to render as pure html, but it would be awesome if there was a solution with more email friendly html
Because the layout of these gets fairly complex, it may also be advantageous to render page as image and insert that image into email body?
I only really know HTML Email, and basics of React - and SO is not great for recommendations of software type questions - so I'll just speak to the email side.
If you can get HTML, you need to consider a few things.
First, anything over two columns is likely to run out of space. You would need to consider a stackable column structure with repeated headers. That would require hiding the duplicated headers for desktop views, since the tables would be separate due to the way we do stacked columns in emails (as inline-blocks without media queries). See https://medium.com/#nathankeenmelb/bulletproof-responsive-datatables-in-html-emails-64248b9e18f5 for full details.
Second, only some approaches would work like that. Images then would be your go-to option. A nice output for table images would be:
<img src="https://via.placeholder.com/600x500" width="600" style="vertical-align:middle;width:100%;border:0">
The link goes to the image itself so you can zoom and move around easier, and get maximum realestate.
An alternative built on that idea would be to have a link from the image to landing page with full web capabilities. That would take longer to load, but may be well worth it.
Since that's probably the most viable, I'll explain these choices of attributes and styles:
Use the width attribute width="600" because that's what Outlook desktop uses
Use inline styles for those email clients that do not support <style> blocks
Vertical-align:middle (or display:block) removes the space underneath the image that some email clients add
width:100% makes it responsive to mobiles
border:0 ensures no border is shown because of the link
Third, datatables are so finicky and particular in HTML email. Each table is unique because they have different data in them that responds differently. In normal web design, you can just use a nice reset and get everything working without much thought. In HTML Email, everything needs to be inline, and supported, with fallbacks for those things that are unsupported. So even the core data often needs editing - e.g. if it has long URLs, emails or words you need to add a wrapping span with word-break CSS but also <wbr>s in the middle of it for some email clients to properly wrap.
Datatables don't often come up, and because of these considerations, it's hard to see how they could be automated easily - and hard to build a case for it financially.
On a related note, if you can show the information using card UI, that seems to me to be a much nicer, simpler, more accessible and easier to code solution than datatables. This is about taking the information and redesigning it into card blocks. I talk about that in detail here: https://medium.com/#nathankeenmelb/responsive-datatables-through-card-ui-design-for-email-aca6f3c395a2

Web Application front-end and back-end misunderstanding

I need a bit of guidance/advice. I have decided to build a web application but I’m having difficulty putting all the components together.
I’ve made basic websites in the past but have forgotten a lot of it. I studied JavaScript and Java in the past but I’m a little rusty so if you decide to reply please treat me like a person that’s new to all of this.
Basically I am having difficulty understanding the backend and front end of the whole web application and what exactly I will need. I’ve done some research found out that I will need MySQL, Tomcat server or Apache? (I don’t understand this part), Spring Tool Suite, knowledge of Java and AngularJS for the front-end. I have basic SQL knowledge. I’m having difficulty binding all this together.
The application I am trying to create is a prototype so not a full application. I’d like to be able to enter data into text boxes which is then visually represented on graphs/charts. I understand that AngularJS is capable of achieving this. Is AngularJS the same as JavaScript? Where does Java come in all of this? I thought a web programming language is needed so why is Java used? Is Java used for the backend? What will MySQL be used for and the Tomcat or Apache server also? I prefer to stick to JavaScript/Angular and Java if possible because I haven’t learned any other languages like PHP or C.
I am working on a Mac if anyone is wondering. I have the following already installed on my machine:
Latest JDK
Spring Tool Suite
MySQL
Could anyone please clarify this for me as best as possible? I don’t think it will take a lot for me to understand it all as I do have knowledge in computing but I’m a bit rusty since it’s been a while since I last used it all.
Any help is greatly appreciated!
There's a lot packed into this question. I'll try to answer it all, but bear with me. Because I hope to cover so much ground, keep in mind that a lot of what I say will be imprecise, and you should definitely read up some more on these topics. You're on the verge of entering a whole new world of programming possibilities if you enjoy it, so take your time and try to soak it all in at your own pace.
First, some basics on web technologies. Possibly the most fundamental thing to understand here is the separation between the client and the server. These terms are broadly used in software discussions to refer to the thing processing, storing, and providing data (the server) and the thing allowing the user to request, view, interact with, and make changes to that data (the client) . What exactly the client and server are will vary widely based on what sort of context you're talking about, but in the world of web development:
The client is generally assumed to be a web browser. There are lots of different web browsers (e.g. Chrome, Firefox, Safari, Internet Explorer/Edge, Opera, ...) and they each have their own quirks, but by and large if you don't try anything too fancy and you stick to recent version of browsers your results will be basically the same no matter which browser you use to view your web page.
When talking about "the server", you can be referring to a few things depending on the sentence you use it in: the server-side code you write (more on this in a minute), the piece of software that handles your server-side code and serves your web pages (this would be Apache or Tomcat), or the physical collection of aluminum, silicon, and plastic on which the above software is running (that is, a computer, anything ranging from your laptop to a dedicated machine). For the purposes of this discussion we'll stick to the first two.
As I said earlier, the most important part of the client/server distinction is in the separation of concerns between presenting and enabling interaction with data on the client and processing and storing data on the server. As much as possible, try to keep those separate; it will make your life much easier in the long run. The client code shouldn't have any idea how the data is stored or processed; that's the server's job, and the client shouldn't need to know. Similarly, the code you write on the server shouldn't care in the least how the data is being formatted and presented to the user. Instead, it should try to provide data in a format that is easy to deal with in lots of different ways.
But I'm getting ahead of myself. First we need to talk about the technology questions you asked. So let's drill down a bit.
The Client
Usually, different programming languages are used on the server and the client1. There are three primary languages used in the browser, and each has a distinct purpose that compliments the purpose of the other two. Forgive me (and feel free to skim or skip) if I tread ground you've already covered; I'm writing for the beginner here, so I want to make sure all the bases are covered.
HTML
HTML (the HyperText Markup Language) is the absolute foundation on which web pages are built. HTML's job is to describe the structure of the page and the data being presented in it. HTML separates things into sections, including headers, footers, articles, paragraphs, asides, and other such containers. HTML also tells the browser about images, videos, and flash games, which text or picture should be a link to somewhere else in the web, which text should be emphasized or where you're making a strong point. It can contain forms containing various sorts of input devices, and it can tell the browser where to send that form's content when you submit the form. Put another way, it describes the composition of your document, the relationships between sections of your content, and, to some degree, the purpose of certain sections of the document2.
HTML looks something like this:
<html>
<head>
<title>A Sample Web Page</title>
</head>
<body>
<header>
<h1>Sample Code FTW!</h1>
</header>
<main>
<section id="introduction">
<h1>Introduction</h1>
<h2>Where it all begins...</h2>
<p>
This is the first paragraph of the intro.
</p>
<p>This is the second one.</p>
</section>
<section id="picture-show">
<h1>Pictures</h1>
<h2>They're fun!</h2>
<p>Here is a cat:</p>
<img src="https://i.imgur.com/MQHYB.jpg" />
<p>Here are some more (the internet is full of these things):</p>
<img src="https://i.imgur.com/sHQQJG5.gif" />
</section>
</main>
<footer>
<small>© KenB 2015; All rights reserved. (just kidding, do what you want with it)</small>
</footer>
</body>
</html>
Here's a link to see the above in action: http://codepen.io/kenbellows/pen/GZvmVy
As seen if you clicked that link, you can technically make a whole web page with just HTML. The thing is, it's pretty boring. First, it's very plain; this is because HTML contains no formatting information. It has structure, but no layout, color, typeface, border, or any other presentation-related information; that's the job of CSS3. Second, it's entirely static; this is because HTML isn't made to describe dynamic content or behaviors. HTML is intentionally static. If you want anything to move, change, or react to user interaction, if you want to display any dynamic content based on calculations made on the fly, that's where you need JavaScript.
Learn more about HTML here: https://developer.mozilla.org/en-US/Learn/Getting_started_with_the_web/HTML_basics
CSS
CSS (Cascading Style Sheets) solve the formatting problem. If you're writing a static page that just displays the same content every time you load the page and doesn't require any user interaction, like a blog post, you probably only need HTML and CSS.
Here's just a little CSS for that HTML I posted up there:
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #333;
background-color: #ccc;
}
header, main, footer {
margin: 1em auto;
width: 60%;
padding: 1em;
}
header {
text-align: center;
}
header > h1 {
font-size: 4em;
}
main {
background-color: #fff;
}
main h1 {
font-size: 2.5em;
margin-bottom: 0;
}
main h2 {
font-size: 1.5em;
margin-top: 0;
}
And a link: http://codepen.io/kenbellows/pen/wGqewE
See what just a little styling can do for a document?
Learn more about CSS: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started
JavaScript
JavaScript is what powers all the dynamic parts of a web page4. This is the most important section for the chart stuff you were talking about. JavaScript, unlike HTML and CSS, is a real, proper programming language, Turing-complete and everything, with all the usual branching, looping, function, and object oriented constructs you would expect from a modern language. Because of this, it's a lot more complex than either HTML or CSS, and it can take as long to master as any other full-fledged programming language.
Learn more about JavaScript here: https://developer.mozilla.org/en-US/Learn/Getting_started_with_the_web/JavaScript_basics
Frameworks
Like any other modern language, JavaScript has plenty of libraries and frameworks written for it to help you handle a lot of the messier, boilerplatier parts of writing a web application. Angular.js, the one you mentioned, is a particularly popular framework at the moment, but you should know that it's only one of many, many frameworks. Don't get me wrong, though, it's a good one. But here's something to keep in mind: if you're just starting out with JavaScript as a language, it might not be the best idea to jump head first into a framework. For one, you're just compounding the amount of knowledge you'll need to get up and running; for another, and this is very important, you should probably learn the language in its own right before you start with a framework, to avoid becoming dependent on that framework. I've known a few too many developers who started with Angular right away, then a year later didn't have a solid grasp of why the code was behaving the way it was because they didn't take the time to get a firm understanding of the language fundamentals. Angular is wonderful, I use it all the time, but again, do yourself a favor and at least go through the MDN tutorial on JavaScript I linked above and try writing a couple toy applications before jumping into Angular.
A thought on your app idea
I actually think that for the purposes of your application, you don't need the server at all, other than for hosting it if you decide to publish it on the web or on your company's intranet or something. I'll talk about the server briefly below to answer your questions, but really, if all you need is to take in some user data and show it in real-time as a chart, you can do that with just some JavaScript. Angular would definitely be helpful since you sound like you want real-time updating charts. There are a few Angular-based chart/graph libraries out there that you should look into, e.g. https://jtblin.github.io/angular-chart.js/
The Server
Generally, the server handles data processing and storage. Instead of going into theory like I did for the client, let me answer your questions directly:
Tomcat and Apache - Tomcat and the Apache HTTP Server are two options for web servers. (These guys fit the second definition of "server" I gave above.) They are definitely popular choices, though Apache tends to be more popular for production servers, and Tomcat for development setups (in my experience; people argue about this all the time).
Spring - Spring, including all its various modules and tooling (SpringMVC, Spring Security, Spring Tool Suite, etc), is a Java framework to help you write your server code (server definition #1). In my personal opinion (worth what you're paying for it), Spring is great for large, complex applications with lots of moving parts, but is unnecessarily complicated for a simple app like the one you described.
MySQL - MySQL, like all flavors of SQL, is a database program. It stores data in tables and provides an interface for you to query that data in all sorts of convenient ways. Databases are great, and MySQL is a popular choice, but it's important to figure out whether you need a database for your project. Are you planning to store the data entered by the user for later use? If not, skip the database.
Other languages - Web server code can be written in any language you can run on the command line. If you like Java and you're good at it, stick with Java. If you want to be adventurous, maybe look into Node.js, a JavaScript server solution; you're learning JavaScript anyway, right? It's all about personal preference and what will get the job done for you. No need to learn PHP (and definitely no need to learn C, good god; please don't write your server code in C) just to write the backend for a simple app like the one you've got. Sounds like you're already learning a lot for this project; no need to add more to your plate.
1. (Might be best to read this footnote again after you're done with everything above.) One notable exception that's becoming more popular is the use of JavaScript on the server-side using Node.js. If you try JavaScript on the client-side and fall in love (like many of us do), maybe give Node a shot.
2. Read up on semantic markup once you've got the basics of how HTML works.
3. To be slightly more accurate, HTML shouldn't contain any of this information, although it technically can contain some of it. This is a holdover from the pre-CSS days of the late-90s/early-2000s, when a lot of sizing, font, and color information was stored in the markup. Please, do yourself a favor: leave formatting to CSS.
4. With the exception of some more advanced CSS rules you can use to get pretty basic hover-effects and simple animation. JavaScript is still necessary for anything involving calculations, iteration, logic, basically anything non-trivial.
What you are building is generally called a "full-stack" web application.
Apache alongside Tomcat is used for transferring data between the front and back ends of the application. Specifically, Tomcat is where your Java code will live in the form of Servlets and JSPs (Java Server Pages). Java (like PHP) is only found on the back-end, and is used for "gluing" together the webpages. The back-end is responsible for connecting & talking with the database (MySQL) for storing data as well as moving data from one place to another.
Your front-end is all the HTML, CSS, and JavaScript of the application. It sends HTTP requests to the back-end in order to send/receive data to/from the back-end. Usually, you only need to reference the back-end when a user submits a form or needs to load more information (using AJAX) or even just a whole new page.
AngularJS is a special creature. It IS JavaScript, so it lives on the front-end and does front-end type things, but (other than communicating with the database) it pretty much replaces the back-end in modern web applications. AngularJS is a tool for creating a "single-page application". Which means that when you would normally be requesting new pages from the back-end, instead you would be requesting modifications of the current page.

Is there an automated way to document Nancy services?

Is there any way to auto-generate Swagger documentation (or similar) for a Nancy service?
I found Nancy.Swagger, but there's no information on how to use it and the demo application doesn't seem to demonstrate generating documentation (if it does, it's not obvious).
Any help would be appreciated. Thanks!
In my current project I've been looking a lot into this problem. I used both nancy.swagger and nancy.swagger.attributes.
I quickly discarded Nancy.swagger, because for me personally it doesn't sound right that you have to create a pure documentation class for each nancy module. The attributes solution was a bit "cleaner" - at least codebase and documentation were in one place. But very fast this became unmaintainable. Module code is unreadable because of many attributes. Nothing is generated automatically: you have to put path, all parameters, even http method as an attribute. This is a huge effort duplication. Problems came very fast, a few examples:
I changed POST to PUT in Nancy and forgot to update [Method] attribute.
I added a parameter but not the attribute for it.
I changed parameter from path to query and didn't update the attribute.
It's too easy to forget to update the attributes (let alone documentation module solution), which leads to discrepancies between your documentation and actual code base. Our UI team is in another country and they had some trouble using the APIs because docu just wasn't up-to-date.
My solution? Don't mix code and documentation. Generating docu from code (like Swashbuckle does) IS ok, but actually writing docu in code and try to dublicate the code in docu is NOT. It's not better than writing it in a Word document for your clients.
If you want Swagger docu, just do it the Swagger way.
- Spend some time with Swagger.Editor and really author your API in
YAML. It looks all-text and hard, but once you get used to it, it's
not.
- Spend some time with Swagger.Codegen and adapt it (it already does a fair job for generating Nancy server code and with a few
adjustments to moustache templates it was just what I needed).
- Automate your process: write a couple of batches to generate your modules and models from yaml and copy them to your repository.
Benefits? Quite a few:
-
Your YAML definition is now the single truth of your REST contract.
If somewhere something is defferent, it's wrong.
Nancy server code is auto-generated
Client code-bases are auto-generated (in our case it's android, ios and angular)
So whenever I change something in REST contract, all codebases are regenerated and added to projects in one batch. I just have to tell the teams something was updated. They don't have to look through some documents and search for it. They just have their code regenerated and probably see some compile errors, in case of breaking changes.
Do I still use nancy.swagger(.annotations)?
Yes, I do use it in another project, which has just one endpoint with a couple of methods. They don't change often. It's not worth the effort to set up everything, I have my swagger docu fast up and running. But if your project is big, API is changing, and you have multiple code-bases depending on your API, my advice is to invest some time into a real swagger setup.
I am quoting the author answer here from https://github.com/khellang/Nancy.Swagger/issues/59
The installation should be really simple, just pull down the NuGet package, add metadata modules to describe your routes, and hit /api-docs. That should get you the JSON. If you want to add swagger-ui as well, you have to add that manually right now.
No. Not in an automated. https://github.com/yahehe/Nancy.Swagger needs lots of manually created metadata.
There is a nice article here: http://www.c-sharpcorner.com/article/generating-api-document-in-nancy-using-swagger/
Looks like you still have to add swagger-ui separately.

Using Skue or similar frameworks to build REST API on google-app-engine

Searching for ways to build REST APIs, I found skue (https://code.google.com/p/skue/). However there is not much information on the site. My plan is to build a rest api as follows strictly:
Models << Business logics << Restful Resources.
What this means is: the models are access exclusively by the business logic; the restful resources interface is the only layer a client has direct access to. I am specifying all this to avoid people suggesting using the appengine-rest-server.
My question is: has anyone ever successfully used Skue? If so do you have any examples you would not mind sharing? GET and POST would be sufficient, but more is welcomed. If not Skue, are there any frameworks out there that allow building such rest-apis on top of the google-app-engine?
I'm the author of Skuë. Skuë means "mouse" in Bribrí which is the language of an indigenous group of people of Costa Rica, my Country.
I know there isn't enough information on the site: (https://code.google.com/p/skue/)
For developers that want to use it on their own projects. I'm sorry for that I just haven't had the time to do a proper documentation since this is just a side project and not my daily work.
However, I'm willing to help you out with ramping up so you will be able to use it. The first thing to notice is the small example that it's part of the source code. Go to the site then click on Source -> Browse and then expand the "app" branch.
The code inside of the "app" folder represents your own API implementation. The package "skue" contains the actual implementation of the library so basically you just create your Python project for Google App Engine and includes the skuë package directly into it.
Now overwrite your main.py file with the content of the downloaded main.py: main.py on Skuë project.
The most important part of that file is where you put your own routes to your resources implementations: Notice here the use of the "ContactResource".
TASK_HANDLERS = [
]
API_HANDLERS = [
('/contacts/(.*)', ContactResource)
]
API_DOC = [ ('/', ApiDocumentationResource) ]
Browse to the contact resource implementation.
There are a lot of things going on under the hood there.. but the idea is for you to not worry about those.
You need to inherit from the proper Resource parent class depending on the kind of resource you want to create, there are four basic types:
DocumentResource: A document resource is a singular concept that is akin to an object instance or database record.
CollectionResource: A collection resource is a server-managed directory of resources. Clients may propose new resources to be added to a collection. However, it is up to the collection to choose to create a new resource, or not.
StoreResource: A store is a client-managed resource repository. A store resource lets an API client put resources in, get them back out, and decide when to delete them.
ControllerResource: A controller resource models a procedural concept. Controller resources are like exe- cutable functions, with parameters and return values; inputs and outputs.
Like a traditional web application’s use of HTML forms, a REST API relies on controller resources to perform application-specific actions that cannot be logically mapped to one of the standard methods (create, retrieve, update, and delete, also known as CRUD).
Now take a look at the "describe_resource" implementation on ContactResource example. When you inherit from the basic resource types described above the next step is to programmatically describe your resource to the outside world using that method. The underlying Skuë implementation uses that method to validate require parameters and also to self describe the endpoints when you perform an OPTIONS request on them.
And the final step is for you to implement the methods (CRUD) that you want to handle for your resource.
Again with the ContactResource example, that resource handles the creation, update and read of Contact items.
I hope this helps you at least to understand how to start using the library. I will create better tutorials in the future, though.
In the meantime you can contact me via email: greivin.lopez#gmail.com and I will send you a more elaborated example or even something that matches your requirements.
Important Note: Currently the Skuë project only supports responses in JSON format. If you plan to use another format you will need to create the proper classes to handle it.
Greetings from Costa Rica.
I haven't used skue, but what you're looking for sounds like a good fit for Google Cloud Endpoints. See my previous answers on the subject for more details.

White labeling CakePHP: What's the best way to provide customization hooks/callbacks to implementers?

I'm developing a CakePHP application that we will provide as a white label for people to implement for their own companies, and they'll need to have certain customization capabilities for themselves.
For starters, they'll be able to do anything they want with the views, and they can add their own Controllers/Models if they need to add completely new stuff. However, I'd rather advise against touching my controllers and models, to make version upgrading easier.
Esentially, the customization capabilities I'm planning to give them are going to be quite basic, I just need to call "something" when certain things happen, so they can do things like update external systems, e-mail themselves/the clients, things like that.
I'm wondering what's the best way to do this?
My plan is to have a "file" (with one class) for each controller of mine, to keep things reasonably organized. This file will have a bunch of empty methods that my code will call, and they'll be able to add code inside those methods to do whatever they need to do.
The specific question is, should this class full of empty methods be a Component? A Controller? Just a regular plain PHP class?
I'll need to call methods in this class from my Controllers, so I'm guessing making it a Controller is out of the question (unless maybe it's a controller that inherits from mine? or mine inherits from theirs, probably).
Also, I'd need the implementer of these methods to have access to my Models and Components, although I'm ok with making them use App::Import, I don't need to have the magic $this->ModelName members set.
Also, does this file I create (etiher Component or Controller) have to live in the app folder next to the other (my) controllers/components? Or can I throw it somewhere separate like the vendors folder?
Have you done something like this before?
Any tips/advice/pitfalls to avoid will be more than welcome.
I know this is kind of subjective, I'm looking to hear from your experience mostly, if you've done this before.
Thanks!
Two ideas that spring to mind:
create abstract templates (controllers, models, whatever necessary) that your clients can extend
write your controllers/components/models as a plugin within their own namespace
Ultimately you seem to want to provide an "enhanced" Cake framework, that your clients still have to write their own Cake code in (I don't know how this goes together with your idea of "basic customization capabilities" though). As such, you should write your code in as much an "optional" manner as possible (namespaced plugins, components, AppModel enhancements, extra libs) and provide documentation on how to use these to help your clients speed up their work.
I would setup a common set of events and use something like the linked to event system to handle this.
That lets the clients manage the event handler classes (read the readme to see what I mean) and subscribe to and broadcast events application-wide.
Also - if you want to have your users not muck about with your core functionality I recommend you package your main app as a plugin.
http://github.com/m3nt0r/eventful-cakephp

Resources