nuxtjs - international javascript conference...vuex vue.js is an open-source...
TRANSCRIPT
NuxtJSBasic principlesAuthentication/Authorisation PluginsContent API
ARISTOS MARKOGIANNAKIS
@arismarko
Senior Developer with years ofexperience. teacher, mentor,community leader @cityjsconf@jsmontlylondon
I am always trying new things. Duringthe past few years I have been tryingstatic website generators
About me
@ARI
SMAR
KO
@ARISMARKO
CodeStructureLets take a step back to the time,those days when we were usinggulp, grunt, and even nowwebpack.
We were all trying to create astructure for our components.
We were all coming up with similarsolutions, but we were luckingconistency.
Hunting for astructureTwo years ago I was thinking howto do develop the CityJS Conferencewebsite.
I wanted to learn Vue, and I startedlooking a good structure for myVueJS project work.
When I came through NuxtJS and Ifelt in love with it. Why?!
@ARISMARKO
NuxtJSWhat is NuxtJS
Nuxt.js is a free and open sourceweb application framework basedon Vue.js, Node.js, Webpack andBabel.js. The framework isadvertised as a "meta-frameworkfor universal applications".
Through my talk I will explain anumber of features but I willshowcase an application that I builtand how you can you useauthentication/authorisation.
Authentication
Routing
Middleware
Plugins
PagesSSR
SSRServer-side rendering (SSR), is theability of an application tocontribute by displaying the web-page on the server instead ofrendering it in the browser.
Server-side sends a fully renderedpage to the client; the client'sJavaScript bundle takes over whichthen allows the Vue.js appto hydrate.
Getting started
JavaScripr or TypeScriptESlintSSR or Single App Rendering modeDeployment target
We need to follow 3 Steps to getstarted
The CLI is asking you, if you wouldlike to install the project, with
USE THE CLI
npx create-nuxt-app <project-name>
The folder where we addour components
Componentsfolder
@ARI
SMAR
KO
The folder with all thepages and where routingis defined.
PagesStructureLets take a look on thestructure of the applicationonce we download it.
We can use Vuex forstoring our state
Store
Our centralised configfile
nuxt.config.js
StructureOur folder structure is whatyou see at the right.
Most commonly foldersused are the components.pages, and files such asnuxt.config.js
PagesOur site is fairly simple, since ourconference is based in UK, most ofthe people go crazy for football. Idecided to create a Football AllStars website.
There are 4 pages:
Home page - Lists Player of month
Team page - Lists all players
Player page - For every player tocheck their stats
Managers page - Where he checkseach players stats
Pages login.vue
player.vueindex.vue
team.vue
manager.vue
LayoutsRouting is easy as we justneed to create a pageinside the pages folder.
This layout will be used by the LoginComponent
Login Layout
This layout will be used by the rest of thecomponents
Default Layout
@ARI
SMAR
KO
LayoutsYou can see that all thepages have a commonlayout except from thelogin page
default.vue(we dont need to declare it)
Declaring a custom layout
nuxt.configThrough this centralisedfile we can control ourapp.
We will make use of thismain times through ourdemo and whilst ondevelopment
Change meta tags for SEO
Head
Define plugins
Plugins
Frame the problems effectively as it will setthe stage of your entire pitch.
Set the cookie forauthentication
@ARI
SMAR
KO
PagesRouting is easy as we justneed to create a pageinside the pages folder.
The filename is the actual route, we canalso make dynamic routes which is quitecool
We dont need routing
We can expand the basic features to addauthorisation in our project
Authentication each page
Adding a special meta-tag we can alsoenable authorisation.
Roles
@ARI
SMAR
KO
AuthenticationAuthentication is the act ofproving an assertion, such asthe identity of a computersystem user. In contrast withidentification, the act ofindicating a person or thing'sidentity, authentication is theprocess of verifying thatidentity.
@ARI
SMAR
KO
AuthorisationAuthorization is the functionof specifying accessrights/privileges to resources,which is related toinformation security andcomputer security in generaland to access control inparticular.
@ARI
SMAR
KO
Pages basedAuthenticationAccess page per user
- Anonymous User Home, Team - Player Player page - Manager Managers page
@ARI
SMAR
KO
@ARI
SMAR
KO
Pages basedAuthenticationAccess page per user
middleware property makes this aprivate page
meta property is used for the roles
For Vue we are making use of Vuex
Store
At the route of the store folder the index.jsfile has the, main store which is used for theauthentication
Default Store
The store keeps track of the authenticateduser and keeps track of the authUser
We save the user in the session, using thelogin and logout functions
How?
VuexVue.js is an open-sourcemodel–view–viewmodelJavaScript framework forbuilding user interfacesand single-pageapplications.
It was created by EvanYou, and is maintained byhim and the rest of theactive core teammembers coming fromvarious companies suchas Netlify and Netguru. @A
RISM
ARKO
VuexCommunicating with thedummy API
Setting the AuthenticatedUser to the Store
We make use of the nuxtRouter to push back tohome
Login APIrouteWe are authenticating the user.
The result of the authenticationis an array - if empty then 401
If the user found for the rightcredentials. - Write the user in session (writes a cookie)- Return the user in the response
Creating adummy apiUsing the serverMiddleware weare creating our Dummy RestAPI
Users can have a role key so inour example, role for themanager is 1, where role for theplayer is 2
serverMiddlewareNuxt internally createsa connect instance that we canadd our own custom middlewareto.
This allows us to registeradditional routes(typically /api routes) withoutneed for an external server.
Here is where we also define ourcookie and for example howlong last before it gets deleted.
MiddlewareMiddleware lets you define customfunctions that can be run beforerendering either a page or a group ofpages (layout).
A middleware receives the context asthe first argument.
MiddlewareYou can create named middleware bycreating a file insidethe middleware/ directory, the filename will be the middlewarename.middleware/authenticated.js
We check the logged in Auth numberagainst the page and if it is equal weallowe to access this page, otherwisethe we sent a 401 error.
If the user is not logged in we sentthe user to the login page
Manager's PageOn this page only the Manager can. login but not the players
Players's PageOn this page a manager can login aswell as a player
PluginsSetting up plugins on nuxt config andthen using them.
One great example is the trend mapslets have a look how we could set itup
First thing is to save a file where wefirst import the library and then usingVue.use we can load the library in theglobal scope.
PluginsSetting up plugins on nuxt config andthen using them.
One great example is the trend mapslets have a look how we could set itup
We declare our plugins in thenuxt.config.js and also declare if wewant to load under ssr or not usingthe flag ssr, in this case the accordionwe say true but we could also writefalse.
Plugin use insideour componentWe can use the component directlywithout having the need to declare it.
Plugin use insideour componentWe can use the component directlywithout having the need to declare it.
@ARISMARKO
Whats nuxt?Content
ContentOne of the coolestfeatures of the currentversion is the content
npm install @nuxt/content
Install the module
export default { modules: ['@nuxt/content']}
Add the module in nuxt.config
mkdir content
Create a content folder
@ARI
SMAR
KO
Player pageWe can create a playerpage.
We want to be able toaccess Cristiano's pageby a smart url
@ARI
SMAR
KO
CREATE OUR PLAYERS SUBFOLDER
CREATE RONALDO MARKDOWN FILE
DynamicPlayerspages
EDIT OUR MARKDOWN FILE
create an players/ directory where we can add ourplayers data
touch content/players/ronaldo.md
# Ronaldo bioCristiano Ronaldo. Ronaldo with Portugal at the 2018 FIFA
works also with csv, yaml, json, json5 or xml.
CustomVariablesOne of the coolest feature ofcontent is the custom variables
@ARISMARKO
CustomVariablesOne of the coolest feature ofcontent is the custom variables
@ARISMARKO
Thank youRepo of demo app:
https://github.com/arismarko/nuxtauth
Q/A
@ARISMARKO