1558928808
Authentication is an important issue when creating a dynamic web application. This article should clear things up and provide a guide to authentication tutorial with Express.js
Building web pages with user authentication can be a huge pain. You typically need to set up some sort of database to manage users even if you’re not using the database for anything else. You would then need to store their password hashes, and you almost need a degree on internet security to know the safest ways to do that.
What if I told you it didn’t have to be so complicated? Using Okta and Express, I’ll show you how to really quickly set up a website that has secure user authentication, without the need for a separate database. Everything you need you could deploy anywhere that you can run Node.
Creating a new app in Express doesn’t take a lot of code. You’ll need to set up your project structure and install some dependencies, which you can do with just a few commands:
mkdir new-project
cd new-project
npm init -y
npm install express@4.16.4 hbs@4.0.1
npm install --save-dev nodemon@1.18.4 standard@12.0.1
Edit the "scripts"
section of your package.json
to look like this:
"scripts": {
"start": "nodemon .",
"test": "standard"
},
Now create a new file index.js
:
index.js
const express = require('express')
const path = require('path')
const app = express()
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'hbs')
app.use(express.urlencoded({ extended: true }))
app.use('/static', express.static('public'))
// @TODO add auth middleware
// @TODO add registration page
// @TODO add logout route
app.use('/', require('./routes/index'))
const port = process.env.PORT || 3000
app.listen(port, () => console.log(`App listening on port ${port}`))
Make a few new folders as well:
mkdir -p public/images routes views
Put a fun greeting image in public/images/greeting.jpg
that you will use to greet users.
Express allows for a templating engine. You already set up Handlebars (hbs) above, so now you can create a couple of views. One will be the HTML skeleton that contains the basic markup, and the other will be your homepage (the index
view).
views/layout.hbs
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
Simple Auth in 15 Minutes
[Navbar](/ "Navbar")
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
{{!-- @TODO add auth links --}}
{{{body}}}
This layout
will get rendered for each view, with the specific view replacing the {{{body}}}
tag.
Now you can create the index
view. This will just display the image you put in public/images/greeting.jpg
:
views/index.hbs

To tell the homepage to use that file when rendering, you’ll also need to create a router. You already require
d routes/index.js
in the index.js file of your app, so now you just need to create that file:
routes/index.js
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.render('index')
})
module.exports = router
The call to res.render('index')
tells Express to use the render the index.hbs
view and respond with the results back to the client. You can also pass in some context, but it’s not needed here just yet.
Now you can run your server with the following command (as you make changes, the server will reload and you’ll just need to refresh the page):
npm start
Go to [http://localhost:3000](http://localhost:3000)
to see your greeting.
You now have a simple web server with a homepage and a lovely greeting image. The next step I promised to show you is to add secure user authentication. This is where Okta comes in to play. Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Our API enables you to:
If you don’t already have one, sign up for a forever-free developer account.
You’re going to need to save some information to use in the app. Create a new file named .env
in the root of your application. In it, enter your organization URL.
HOST_URL=http://localhost:3000
OKTA_ORG_URL=https://{yourOktaOrgUrl}
You will also need a random string to use as an App Secret for sessions. You can generate this with the following command:
npm install -g uuid-cli
echo "APP_SECRET=`uuid`" >> .env
Next, log in to your Okta developer console, navigate to Applications, then click Add Application. Select Web, then click Next.
The page you come to after creating an application has some more information you need to save to your .env
file. Copy in the client ID and client secret.
OKTA_CLIENT_ID={yourClientId}
OKTA_CLIENT_SECRET={yourClientSecret}
At the time of this writing, the default application creation page does not allow you to add a Logout redirect URI, but you can add one after creating the application. After creating the application, click Edit, then next to Logout redirect URIs click Add URI. Add a logout redirect URI of [http://localhost:3000](http://localhost:3000)
and click Save.
The last piece of information you need from Okta is an API token. In your developer console, navigate to API -> Tokens, then click on Create Token. You can have many tokens, so just give this one a name that reminds you what it’s for, like “15 Minute Auth”. You’ll be given a token that you can only see right now. If you lose the token, you’ll have to create another one. Add this to .env
also.
OKTA_TOKEN={yourOktaAPIToken}
Okta provides some middleware that will give you information about whether the user is registered or not. It also gives you a login page by default at /login
. Add the following dependencies:
npm install dotenv@6.1.0 express-session@1.15.6 @okta/oidc-middleware@1.0.2 @okta/okta-sdk-nodejs@1.2.0
In your index.js
page, replace the // @TODO add auth middleware
comment with the following code:
app.use(require('express-session')({
secret: process.env.APP_SECRET,
resave: true,
saveUninitialized: false
}))
const { ExpressOIDC } = require('@okta/oidc-middleware')
const oidc = new ExpressOIDC({
issuer: `${process.env.OKTA_ORG_URL}/oauth2/default`,
client_id: process.env.OKTA_CLIENT_ID,
client_secret: process.env.OKTA_CLIENT_SECRET,
redirect_uri: `${process.env.HOST_URL}/authorization-code/callback`,
scope: 'openid profile'
})
app.use(oidc.router)
Also, make sure to add the following to the very top of index.js
. This needs to be there before any other code in order to load your environment variables, so it should be the very first line of the file:
require('dotenv').config()
You should now be able to login by going to /login
. This will redirect you to your Okta developer page, and after you sign in you’ll be redirected back to the homepage.
For people who aren’t registered yet, they’ll need a registration page. At the time of this writing, Okta doesn’t provide a registration page out of the box, but you can build one pretty quickly. Create a new view for your route:
views/register.hbs
{{#each fields}}
{{this.label}}
<input
required
name="{{this.name}}"
type="{{this.type}}"
class="form-control {{#if this.error}}is-invalid{{/if}}"
value="{{this.value}}"
/>
{{this.error}}
{{/each}}
Register
You’ll also need a new route:
routes/register.js
const okta = require('@okta/okta-sdk-nodejs')
const express = require('express')
const router = express.Router()
const client = new okta.Client({
orgUrl: process.env.OKTA_ORG_URL,
token: process.env.OKTA_TOKEN
})
// Take the user to the homepage if they're already logged in
router.use('/', (req, res, next) => {
if (req.userContext) {
return res.redirect('/')
}
next()
})
const fields = [
{ name: 'firstName', label: 'First Name' },
{ name: 'lastName', label: 'Last Name' },
{ name: 'email', label: 'Email', type: 'email' },
{ name: 'password', label: 'Password', type: 'password' }
]
router.get('/', (req, res) => {
res.render('register', { fields })
})
router.post('/', async (req, res) => {
const { body } = req
try {
await client.createUser({
profile: {
firstName: body.firstName,
lastName: body.lastName,
email: body.email,
login: body.email
},
credentials: {
password: {
value: body.password
}
}
})
res.redirect('/')
} catch ({ errorCauses }) {
const errors = {}
errorCauses.forEach(({ errorSummary }) => {
const [, field, error] = /^(.+?): (.+)$/.exec(errorSummary)
errors[field] = error
})
res.render('register', {
errors,
fields: fields.map(field => ({
...field,
error: errors[field.name],
value: body[field.name]
}))
})
}
})
module.exports = router
To tie this all together, in your root index.js
file, make sure to replace the // @TODO add registration page
comment with the following:
app.use('/register', require('./routes/register'))
You can now have users register. If they run into an error, it will be displayed with the field that caused the error.
At the time of this writing, Okta’s middleware doesn’t provide a default /logout
route. Luckily, adding one is fairly simple. In your index.js
file, replace the // @TODO add logout route
comment with:
app.get('/logout', (req, res) => {
if (req.userContext) {
const idToken = req.userContext.tokens.id_token
const to = encodeURI(process.env.HOST_URL)
const params = id_token_hint=${idToken}&post_logout_redirect_uri=${to}
req.logout()
res.redirect(${process.env.OKTA_ORG_URL}/oauth2/default/v1/logout?${params})
} else {
res.redirect('/')
}
})
If you’re logged in, this will invalidate the token and delete the user’s session. It will then redirect you back to the homepage. If you’re not logged in, it just takes you back to the homepage.
To more easily expose these routes to the user, you can add some buttons. You’ll need to expose the user context to the view to know if a user is logged in or not so you know which buttons to display, and potentially greet the user.
In routes/index.js
replace the res.render('index')
line with the following:
routes/index.js
const { userContext } = req
res.render('index', { userContext })
While you’re at it, you can also prevent the user from seeing your greeting unless they’re logged in. Change your views/index.hbs
file to the following:
views/index.hbs
{{#if userContext}}
# Hi {{userContext.userinfo.given_name}}!

{{else}}
# Please log in
{{/if}}
Now to add the buttons. In views/layout.hbs
, replace the {{!-- @TODO add auth links --}}
comment with the following:
views/layout.hbs
{{#if userContext}}
[Log out](/logout "Log out")
{{else}}
[Log in](/login "Log in")
[Register](/register "Register")
{{/if}}
Check out the final product to make sure it works
#node-js #express #web-development #security
1632537859
Not babashka. Node.js babashka!?
Ad-hoc CLJS scripting on Node.js.
Experimental. Please report issues here.
Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.
Additional goals and features are:
Nbb requires Node.js v12 or newer.
CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).
Install nbb
from NPM:
$ npm install nbb -g
Omit -g
for a local install.
Try out an expression:
$ nbb -e '(+ 1 2 3)'
6
And then install some other NPM libraries to use in the script. E.g.:
$ npm install csv-parse shelljs zx
Create a script which uses the NPM libraries:
(ns script
(:require ["csv-parse/lib/sync$default" :as csv-parse]
["fs" :as fs]
["path" :as path]
["shelljs$default" :as sh]
["term-size$default" :as term-size]
["zx$default" :as zx]
["zx$fs" :as zxfs]
[nbb.core :refer [*file*]]))
(prn (path/resolve "."))
(prn (term-size))
(println (count (str (fs/readFileSync *file*))))
(prn (sh/ls "."))
(prn (csv-parse "foo,bar"))
(prn (zxfs/existsSync *file*))
(zx/$ #js ["ls"])
Call the script:
$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs
Nbb has first class support for macros: you can define them right inside your .cljs
file, like you are used to from JVM Clojure. Consider the plet
macro to make working with promises more palatable:
(defmacro plet
[bindings & body]
(let [binding-pairs (reverse (partition 2 bindings))
body (cons 'do body)]
(reduce (fn [body [sym expr]]
(let [expr (list '.resolve 'js/Promise expr)]
(list '.then expr (list 'clojure.core/fn (vector sym)
body))))
body
binding-pairs)))
Using this macro we can look async code more like sync code. Consider this puppeteer example:
(-> (.launch puppeteer)
(.then (fn [browser]
(-> (.newPage browser)
(.then (fn [page]
(-> (.goto page "https://clojure.org")
(.then #(.screenshot page #js{:path "screenshot.png"}))
(.catch #(js/console.log %))
(.then #(.close browser)))))))))
Using plet
this becomes:
(plet [browser (.launch puppeteer)
page (.newPage browser)
_ (.goto page "https://clojure.org")
_ (-> (.screenshot page #js{:path "screenshot.png"})
(.catch #(js/console.log %)))]
(.close browser))
See the puppeteer example for the full code.
Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet
macro is similar to promesa.core/let
.
$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)' 0.17s user 0.02s system 109% cpu 0.168 total
The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx
this adds another 300ms or so, so for faster startup, either use a globally installed nbb
or use $(npm bin)/nbb script.cljs
to bypass npx
.
Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.
To load .cljs
files from local paths or dependencies, you can use the --classpath
argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs
relative to your current dir, then you can load it via (:require [foo.bar :as fb])
. Note that nbb
uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar
in the namespace name becomes foo_bar
in the directory name.
To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:
$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"
and then feed it to the --classpath
argument:
$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]
Currently nbb
only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar
files will be added later.
The name of the file that is currently being executed is available via nbb.core/*file*
or on the metadata of vars:
(ns foo
(:require [nbb.core :refer [*file*]]))
(prn *file*) ;; "/private/tmp/foo.cljs"
(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"
Nbb includes reagent.core
which will be lazily loaded when required. You can use this together with ink to create a TUI application:
$ npm install ink
ink-demo.cljs
:
(ns ink-demo
(:require ["ink" :refer [render Text]]
[reagent.core :as r]))
(defonce state (r/atom 0))
(doseq [n (range 1 11)]
(js/setTimeout #(swap! state inc) (* n 500)))
(defn hello []
[:> Text {:color "green"} "Hello, world! " @state])
(render (r/as-element [hello]))
Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core
namespace is included with the let
and do!
macros. An example:
(ns prom
(:require [promesa.core :as p]))
(defn sleep [ms]
(js/Promise.
(fn [resolve _]
(js/setTimeout resolve ms))))
(defn do-stuff
[]
(p/do!
(println "Doing stuff which takes a while")
(sleep 1000)
1))
(p/let [a (do-stuff)
b (inc a)
c (do-stuff)
d (+ b c)]
(prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3
Also see API docs.
Since nbb v0.0.75 applied-science/js-interop is available:
(ns example
(:require [applied-science.js-interop :as j]))
(def o (j/lit {:a 1 :b 2 :c {:d 1}}))
(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1
Most of this library is supported in nbb, except the following:
:syms
.-x
notation. In nbb, you must use keywords.See the example of what is currently supported.
See the examples directory for small examples.
Also check out these projects built with nbb:
See API documentation.
See this gist on how to convert an nbb script or project to shadow-cljs.
Prequisites:
To build:
bb release
Run bb tasks
for more project-related tasks.
Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb
License: EPL-1.0
#node #javascript
1592807820
What is 2FA
Two-Factor Authentication (or 2FA as it often referred to) is an extra layer of security that is used to provide users an additional level of protection when securing access to an account.
Employing a 2FA mechanism is a vast improvement in security over the Singe-Factor Authentication method of simply employing a username and password. Using this method, accounts that have 2FA enabled, require the user to enter a one-time passcode that is generated by an external application. The 2FA passcode (usually a six-digit number) is required to be input into the passcode field before access is granted. The 2FA input is usually required directly after the username and password are entered by the client.
#tutorials #2fa #access #account security #authentication #authentication method #authentication token #cli #command line #cpanel #feature manager #google authenticator #one time password #otp #otp authentication #passcode #password #passwords #qr code #security #security code #security policy #security practices #single factor authentication #time-based one-time password #totp #two factor authentication #whm
1626694620
#stubborndevelopers
In this video we will learn below points:
************ Node.JS Tutorial in English 2021 Playlist ************
https://www.youtube.com/watch?v=gs0X92Yx70s&list=PLllIEssCHLKdNEVWsBQ5zcCxLu8Xpsl0E&index=2
************ React.JS Tutorial in Hindi 2021 Playlist ************
https://www.youtube.com/watch?v=F2A1qXcskP8&list=PLllIEssCHLKdRqOrDJdPIeW7nrwPPfa46
#node.js #express.stati #css #js #express js
React Interview Questions & Answers
1625597880
Today we are going to look at how we can use Express EJS Layouts to help us with website templating which ultimately help us to avoid writing duplicated code as well as making our website/application easily maintainable.
I had to cut off the intro as the music was too lound.
SOURCE FILES
https://raddy.co.uk/blog/nodejs-express-layouts-and-partials/
CONNECT with RaddyTheBrand
Website: https://www.raddy.co.uk
GitHub: https://www.github.com/RaddyTheBrand
Instagram: https://www.instagram.com/RaddyTheBrand
Twitter: https://www.twitter.com/RaddyTheBrand
Newsletter: https://www.raddy.co.uk/newsletter
DONATE to RaddyTheBrand
BuyMeACoffee: https://www.buymeacoffee.com/RaddyTheBrand
PayPal: https://bit.ly/3tAuElv
#partials #ejs #node.js #node #express #node.js express ejs layouts and partials tutorial
1595334123
I consider myself an active StackOverflow user, despite my activity tends to vary depending on my daily workload. I enjoy answering questions with angular tag and I always try to create some working example to prove correctness of my answers.
To create angular demo I usually use either plunker or stackblitz or even jsfiddle. I like all of them but when I run into some errors I want to have a little bit more usable tool to undestand what’s going on.
Many people who ask questions on stackoverflow don’t want to isolate the problem and prepare minimal reproduction so they usually post all code to their questions on SO. They also tend to be not accurate and make a lot of mistakes in template syntax. To not waste a lot of time investigating where the error comes from I tried to create a tool that will help me to quickly find what causes the problem.
Angular demo runner
Online angular editor for building demo.
ng-run.com
<>
Let me show what I mean…
There are template parser errors that can be easy catched by stackblitz
It gives me some information but I want the error to be highlighted
#mean stack #angular 6 passport authentication #authentication in mean stack #full stack authentication #mean stack example application #mean stack login and registration angular 8 #mean stack login and registration angular 9 #mean stack tutorial #mean stack tutorial 2019 #passport.js