session-sync-auth-site 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -99,6 +99,46 @@ setUpSessionSyncAuthRoutes({
99
99
  })
100
100
  ```
101
101
 
102
+ ## Admin backend functions
103
+
104
+ ```js
105
+ const { createUser, getLoginLink, updateUserAccount } = require('session-sync-auth-site')
106
+
107
+ app.post(`create-user`, (req, res, next) => {
108
+ const userId = await createUser({
109
+ email: req.body.email,
110
+ req,
111
+ })
112
+ res.send({ userId })
113
+ })
114
+
115
+ app.post(`get-login-link`, (req, res, next) => {
116
+ const loginLink = await getLoginLink({
117
+ email: req.body.email,
118
+ redirectUrl: req.body.redirectUrl, // optional
119
+ req,
120
+ })
121
+ res.send({ loginLink })
122
+ })
123
+
124
+ app.post(`update-user-account`, (req, res, next) => {
125
+ await updateUserAccount({
126
+ userId: req.body.userId,
127
+ data: { // only include details being updated
128
+ name: req.body.name,
129
+ email: req.body.email,
130
+ image: req.body.image,
131
+ language: req.body.language,
132
+ terms: req.body.terms,
133
+ image: req.body.image,
134
+ gender: req.body.gender,
135
+ },
136
+ req,
137
+ })
138
+ res.send({ success: true })
139
+ })
140
+ ```
141
+
102
142
  # Frontend usage
103
143
 
104
144
  ```html
@@ -141,7 +181,9 @@ setUpSessionSyncAuthRoutes({
141
181
 
142
182
  <button onclick="javascript:window.sessionSyncAuth.getAccessToken()">Get Access Token</button>
143
183
 
144
- <button onclick="javascript:window.sessionSyncAuth.logIn()">Log in</button>
184
+ <button onclick="javascript:window.sessionSyncAuth.logIn()">Sign in</button>
185
+
186
+ <button onclick="javascript:window.sessionSyncAuth.updateAccount()">Update my account</button>
145
187
 
146
188
  <button onclick="javascript:window.sessionSyncAuth.getUser()">Get user</button>
147
189
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "session-sync-auth-site",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "main": "src/index.js",
5
5
  "repository": {
6
6
  "type": "git",
@@ -71,7 +71,7 @@ const authenticate = ({
71
71
  .map(key => {
72
72
  const safeKey = key.replace(/[`\s]/g, '')
73
73
  return (
74
- `AND \`${safeKey}\` = :${safeKey}`
74
+ `AND u.\`${safeKey}\` = :${safeKey}`
75
75
  )
76
76
  })
77
77
  .join('\n')
@@ -0,0 +1,43 @@
1
+ const jwt = require('jsonwebtoken')
2
+
3
+ const createUser = async ({
4
+ email,
5
+ req, // either this or `setup` is required
6
+ setup, // keys: siteId, authDomain, and jwtSecret
7
+ }={}) => {
8
+
9
+ const {
10
+ siteId,
11
+ authDomain,
12
+ jwtSecret,
13
+ protocol=req.sessionSyncAuthProtocol || `https`,
14
+ } = setup || await req.getSessionSyncAuthSetupInfo()
15
+
16
+ const createUserResult = await fetch(
17
+ `${protocol}://${authDomain}/api/create-user`,
18
+ {
19
+ method: 'post',
20
+ body: JSON.stringify({
21
+ siteId,
22
+ jwtData: jwt.sign(
23
+ {
24
+ email,
25
+ },
26
+ jwtSecret,
27
+ ),
28
+ }),
29
+ headers: {
30
+ 'Content-Type': 'application/json',
31
+ },
32
+ },
33
+ )
34
+
35
+ if(createUserResult.status !== 200) throw new Error(`User creation failed: ${createUserResult.statusText} [${createUserResult.status}]`)
36
+ const { success, userId } = await createUserResult.json()
37
+ if(!success) throw new Error(`User creation failed: bad result from auth server`)
38
+
39
+ return userId
40
+
41
+ }
42
+
43
+ module.exports = createUser
@@ -0,0 +1,48 @@
1
+ const jwt = require('jsonwebtoken')
2
+
3
+ const getLoginLink = async ({
4
+ email,
5
+ redirectUrl, // defaults to req.headers.origin
6
+ req, // either this or `setup` is required
7
+ setup, // keys: siteId, authDomain, and jwtSecret
8
+ }={}) => {
9
+
10
+ redirectUrl = redirectUrl || req.headers.origin
11
+
12
+ const {
13
+ siteId,
14
+ authDomain,
15
+ jwtSecret,
16
+ protocol=req.sessionSyncAuthProtocol || `https`,
17
+ } = setup || await req.getSessionSyncAuthSetupInfo()
18
+
19
+ const origin = (redirectUrl.match(/^https?:\/\/[^/]+/, '') || {})[0]
20
+ const loggedInRedirectUrl = `${redirectUrl}${/\?/.test(redirectUrl) ? `&` : `?`}action=successfulLogin&origin=${encodeURIComponent(origin)}&accessToken=ACCESS_TOKEN`
21
+
22
+ const getLoginLinkResult = await fetch(
23
+ `${protocol}://${authDomain}/api/get-login-link`,
24
+ {
25
+ method: 'post',
26
+ body: JSON.stringify({
27
+ siteId,
28
+ jwtData: jwt.sign(
29
+ {
30
+ email,
31
+ loggedInRedirectUrl,
32
+ },
33
+ jwtSecret,
34
+ ),
35
+ }),
36
+ headers: {
37
+ 'Content-Type': 'application/json',
38
+ },
39
+ },
40
+ )
41
+
42
+ if(getLoginLinkResult.status !== 200) throw new Error(`Login link creation failed: ${getLoginLinkResult.statusText} [${getLoginLinkResult.status}]`)
43
+
44
+ return await getLoginLinkResult.text()
45
+
46
+ }
47
+
48
+ module.exports = getLoginLink
package/src/index.js CHANGED
@@ -1,7 +1,13 @@
1
1
  const authenticate = require('./authenticate')
2
2
  const setUpSessionSyncAuthRoutes = require('./setUpSessionSyncAuthRoutes')
3
+ const createUser = require('./createUser')
4
+ const updateUserAccount = require('./updateUserAccount')
5
+ const getLoginLink = require('./getLoginLink')
3
6
 
4
7
  module.exports = {
5
8
  authenticate,
6
9
  setUpSessionSyncAuthRoutes,
10
+ createUser,
11
+ updateUserAccount,
12
+ getLoginLink,
7
13
  }
@@ -6,6 +6,8 @@
6
6
  defaultOrigin = origin
7
7
  }
8
8
 
9
+ const addOnQueryStrConnectorChar = href => `${href}${/\?/.test(href) ? `&` : `?`}`
10
+
9
11
  const getLocalStorageOrCookieItem = item => {
10
12
  if(enableSSR) {
11
13
  const desiredCookieNameAndValue = (
@@ -43,18 +45,28 @@
43
45
  return queryStringAddOn
44
46
  }
45
47
 
46
- const logIn = async ({ origin=defaultOrigin, extraQueryParamsForCallbacks, loggedInRedirectHref }={}) => {
47
- const cancelRedirectUrl = `${location.href.replace(/\?.*$/, '')}?action=canceledLogin&origin=${encodeURIComponent(origin)}${getQueryStringAddOn(extraQueryParamsForCallbacks)}`
48
- const loggedInRedirectUrl = `${loggedInRedirectHref || location.href.replace(/\?.*$/, '')}?action=successfulLogin&origin=${encodeURIComponent(origin)}&accessToken=ACCESS_TOKEN${getQueryStringAddOn(extraQueryParamsForCallbacks)}`
48
+ const logIn = async ({
49
+ origin=defaultOrigin,
50
+ extraQueryParamsForCallbacks,
51
+ loggedInRedirectHref=location.href,
52
+ cancelRedirectHref=location.href,
53
+ }={}) => {
54
+ const cancelRedirectUrl = `${addOnQueryStrConnectorChar(cancelRedirectHref)}action=canceledLogin&origin=${encodeURIComponent(origin)}${getQueryStringAddOn(extraQueryParamsForCallbacks)}`
55
+ const loggedInRedirectUrl = `${addOnQueryStrConnectorChar(loggedInRedirectHref)}action=successfulLogin&origin=${encodeURIComponent(origin)}&accessToken=ACCESS_TOKEN${getQueryStringAddOn(extraQueryParamsForCallbacks)}`
49
56
 
50
57
  const queryString = `cancelRedirectUrl=${encodeURIComponent(cancelRedirectUrl)}&loggedInRedirectUrl=${encodeURIComponent(loggedInRedirectUrl)}`
51
58
 
52
59
  window.location = `${origin}/log-in?${queryString}`
53
60
  }
54
61
 
55
- const updateAccount = async ({ origin=defaultOrigin, extraQueryParamsForCallbacks, updatedRedirectHref }={}) => {
56
- const cancelRedirectUrl = `${location.href.replace(/\?.*$/, '')}?action=canceledAccountUpdate&origin=${encodeURIComponent(origin)}${getQueryStringAddOn(extraQueryParamsForCallbacks)}`
57
- const updatedRedirectUrl = `${updatedRedirectHref || location.href.replace(/\?.*$/, '')}?action=successfulAccountUpdate&origin=${encodeURIComponent(origin)}${getQueryStringAddOn(extraQueryParamsForCallbacks)}`
62
+ const updateAccount = async ({
63
+ origin=defaultOrigin,
64
+ extraQueryParamsForCallbacks,
65
+ updatedRedirectHref=location.href,
66
+ cancelRedirectHref=location.href,
67
+ }={}) => {
68
+ const cancelRedirectUrl = `${addOnQueryStrConnectorChar(cancelRedirectHref)}action=canceledAccountUpdate&origin=${encodeURIComponent(origin)}${getQueryStringAddOn(extraQueryParamsForCallbacks)}`
69
+ const updatedRedirectUrl = `${addOnQueryStrConnectorChar(updatedRedirectHref)}action=successfulAccountUpdate&origin=${encodeURIComponent(origin)}${getQueryStringAddOn(extraQueryParamsForCallbacks)}`
58
70
 
59
71
  const queryString = `cancelRedirectUrl=${encodeURIComponent(cancelRedirectUrl)}&updatedRedirectUrl=${encodeURIComponent(updatedRedirectUrl)}`
60
72
 
@@ -21,6 +21,12 @@ const setUpSessionSyncAuthRoutes = ({
21
21
 
22
22
  getSetupInfo = getSetupInfo || (async () => ({ siteId, jwtSecret, authDomain }))
23
23
 
24
+ app.use((req, res, next) => {
25
+ req.getSessionSyncAuthSetupInfo = () => getSetupInfo(req)
26
+ req.sessionSyncAuthProtocol = protocol
27
+ next()
28
+ })
29
+
24
30
  app.get(getUser, (req, res, next) => {
25
31
  res.json({
26
32
  status: req.user ? 'Logged in' : 'Not logged in',
@@ -0,0 +1,42 @@
1
+ const jwt = require('jsonwebtoken')
2
+
3
+ const updateUserAccount = async ({
4
+ userId,
5
+ data,
6
+ req, // either this or `setup` is required
7
+ setup, // keys: siteId, authDomain, and jwtSecret
8
+ }={}) => {
9
+
10
+ const {
11
+ siteId,
12
+ authDomain,
13
+ jwtSecret,
14
+ protocol=req.sessionSyncAuthProtocol || `https`,
15
+ } = setup || await req.getSessionSyncAuthSetupInfo()
16
+
17
+ const updateUserAccountResult = await fetch(
18
+ `${protocol}://${authDomain}/api/update-user-account`,
19
+ {
20
+ method: 'post',
21
+ body: JSON.stringify({
22
+ siteId,
23
+ jwtData: jwt.sign(
24
+ {
25
+ userId,
26
+ data,
27
+ },
28
+ jwtSecret,
29
+ ),
30
+ }),
31
+ headers: {
32
+ 'Content-Type': 'application/json',
33
+ },
34
+ },
35
+ )
36
+
37
+ if(updateUserAccountResult.status !== 200) throw new Error(`User update failed: ${updateUserAccountResult.statusText} [${updateUserAccountResult.status}]`)
38
+ if(!(await updateUserAccountResult.json()).success) throw new Error(`User update failed: bad result from auth server`)
39
+
40
+ }
41
+
42
+ module.exports = updateUserAccount