session-sync-auth-site
v0.5.10
Published
Run `node ./node_modules/session-sync-auth-site/src/createDBTables.js [mysql_connection_string] [user_table_name] [session_table_name]`
Downloads
39
Readme
Setup
Run node ./node_modules/session-sync-auth-site/src/createDBTables.js [mysql_connection_string] [user_table_name] [session_table_name]
Example: node ./node_modules/session-sync-auth-site/src/createDBTables.js mysql://root@localhost/SessionSyncAuthSite users sessions
You may add on more fields to the user and session tables, if you like.
Simple backend usage
const express = require('express')
const app = express()
const cors = require('cors')
const bodyParser = require('body-parser')
const { authenticate, setUpSessionSyncAuthRoutes } = require('session-sync-auth-site')
app.use(cors())
app.use(bodyParser.json())
app.use(authenticate({
// either `connectionObj` or `connectionStr` is required
connectionObj: {
host,
user,
password,
database,
port,
},
}))
setUpSessionSyncAuthRoutes({
app,
siteId,
authDomain,
jwtSecret,
})
Exhaustive options for authenticate with default values
app.use(authenticate({
// either `connectionObj` or `connectionStr` required
connectionObj: {
host,
user,
password,
database,
port,
},
userTableName: 'users',
sessionTableName: 'sessions',
userTableColNameMap: {
// Example:
// updated_at: 'updatedAt',
},
extraUserTableSelectValues: {
// Use this when the user table id column is not unique.
// (Often the case with a multi-tenacy setup.)
// In such a case, add other WHERE parameters here to combine with
// the id column such that combination is unique.
// Note: These parameters will typically coincide with `extraUserTableValues` below.
// Example:
// tenantId: 34,
},
sessionTableColNameMap: {},
}))
Exhaustive options for setUpSessionSyncAuthRoutes with default values
setUpSessionSyncAuthRoutes({
app, // required
siteId, // required (unless getSetupInfo provided)
authDomain, // required (unless getSetupInfo provided)
jwtSecret, // required (unless getSetupInfo provided)
getSetupInfo: req => { // useful for multi-tenancy setups
// fetch the needed values based upon req
return {
siteId,
authDomain,
jwtSecret,
extraUserTableValues, // optional
// Note: In a multi-tenancy setup, `extraUserTableValues` should
// typically coincide with `extraUserTableSelectValues` above.
}
},
mergeUser: async ({ id, mergeToUserId, req }) => { // optional (when absent, merge requests will succeed even though no data is merged for this site)
// move all of user's data to mergeToUserId
},
deleteUser: async ({ id, req }) => { // optional (when absent, the appropriate rows from users and sessions are deleted)
// delete all of user's data, including appropriate rows from users and sessions tables
},
protocol: 'https',
paths: {
getUser: '/get-user',
logIn: '/log-in',
logOut: '/log-out',
authSync: '/auth-sync',
},
languageColType: '639-3', // OPTIONS: '639-1', '639-3', 'IETF'
})
Admin backend functions
const { createUser, getLoginLink, updateUserAccount, deleteUser } = require('session-sync-auth-site')
app.post(`create-user`, (req, res, next) => {
// first check that user is admin with permission to do this
const userId = await createUser({
email: req.body.email,
req,
})
res.send({ userId })
})
app.post(`get-login-link`, (req, res, next) => {
// first check that user is admin with permission to do this
const loginLink = await getLoginLink({
email: req.body.email,
redirectUrl: req.body.redirectUrl, // must begin with the frontend domain (default: req.headers.origin)
origin: `https://my-backend-domain.com`, // default: `${req.protocol}://${req.headers.host}`
req,
})
res.send({ loginLink })
})
app.post(`update-user-account`, (req, res, next) => {
// first check that user is admin with permission to do this
await updateUserAccount({
userId: req.body.userId,
data: { // only include details being updated
name: req.body.name,
email: req.body.email,
image: req.body.image,
language: req.body.language,
terms: req.body.terms,
image: req.body.image,
gender: req.body.gender,
},
req,
})
res.send({ success: true })
})
app.post(`delete-user`, (req, res, next) => {
// first check that user is admin with permission to do this
await deleteUser({
id: req.body.id,
mergeToUserId: req.body.mergeToUserId, // optional
req,
})
res.send({ success: true })
})
Frontend usage
<html>
<head>
<script src="[private_url]/sessionSyncAuthFrontend.js"></script>
<script>
window.sessionSyncAuth.init({
defaultOrigin: 'https://my-backend-domain.com',
callbacks: {
canceledLogin: ({ origin }) => {},
successfulLogin: ({ origin, accessToken }) => {},
canceledAccountUpdate: ({ origin }) => {},
successfulAccountUpdate: ({ origin }) => {},
successfulLogout: ({ origin }) => {},
unnecessaryLogout: ({ origin }) => {},
error: ({ errorMessage }) => {},
},
// enabledSSR: true, // Include this if you use server-side-rendering
})
// To change the default origin...
// window.sessionSyncAuth.setDefaultOrigin('https://my-backend-domain.com')
// When getting data from your backend via AJAX, add in a x-access-token header...
// const response = await fetch(url, {
// headers: {
// 'x-access-token': window.sessionSyncAuth.getAccessToken(),
// },
// })
</script>
<head>
<body>
<!-- All functions below can also take a single options parameter with an `origin` key. -->
<button onclick="javascript:window.sessionSyncAuth.getAccessToken()">Get Access Token</button>
<button onclick="javascript:window.sessionSyncAuth.logIn()">Sign in</button>
<button onclick="javascript:window.sessionSyncAuth.updateAccount()">Update my account</button>
<button onclick="javascript:window.sessionSyncAuth.getUser()">Get user</button>
<button onclick="javascript:window.sessionSyncAuth.logOut()">Log out</button>
</body>
</html>