Search…
Correlating Users Between Passage and Your Database

Introduction

Once you've added Passage authentication to your application, you need to be able to retrieve data about or perform actions on your users all while ensuring they are properly authenticated. In this guide, we will walk through the easiest way to correlate a Passage User with a user of your application.

Authenticating Users

Each Passage SDK has an authenticateRequest function that is used to verify Passage Auth Tokens in your backend application before allowing requests to proceed. Most commonly, this is done in a middleware function for all requests that require authentication.
The authenticateRequest function in the Passage SDK returns the Passage User ID, which should be set in the request context so that it can be accessed throughout the code processing the request.
Node.js
Go
Python Flask
1
import Passage from "@passageidentity/passage-node";
2
​
3
// passage middleware
4
let passage = new Passage(passageConfig);
5
let passageAuthMiddleware = (() => {
6
return async (req, res, next) => {
7
try {
8
let userID = await passage.authenticateRequest(req);
9
if (userID) {
10
// user is authenticated
11
res.userID = userID;
12
next();
13
}
14
} catch (e) {
15
// unauthorized
16
}
17
};
18
})();
19
​
20
// authenticated route that uses middleware
21
app.get("/auth", passageAuthMiddleware, async (req, res) => {
22
let userID = res.userID;
23
// proceed
24
});
Copied!
1
import (
2
"net/http"
3
"github.com/go-chi/chi/v5"
4
"github.com/passageidentity/passage-go"
5
)
6
​
7
// example using Chi router
8
func (a *API) Handler() http.Handler {
9
r := chi.NewRouter()
10
​
11
r.Use(passageMiddleware)
12
r.Route("/auth", exampleHandler)
13
​
14
return r
15
}
16
​
17
// middleware that authenticates requests and sets
18
// passage user id in context
19
func (a *API) passageMiddleware(next http.Handler) http.Handler {
20
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
21
psg, _:= passage.New("<PASSAGE_APP_ID>", nil)
22
user, err := psg.AuthenticateRequest(r)
23
if err != nil {
24
// unauthorized
25
}
26
​
27
ctx := context.WithValue(r.Context(), ctxPassageUser, user)
28
next.ServeHTTP(w, r.WithContext(ctx))
29
})
30
}
31
​
32
// example handler that uses passage middleware
33
func exampleHandler(w http.ResponseWriter, r *http.Request) {
34
userID := r.Context().Value(ctxPassageUser).(string)
35
// βœ… Authentication successful. Proceed...
36
​
37
}
Copied!
1
from flask import Blueprint, g, render_template, request
2
from passageidentity import Passage, PassageError
3
​
4
@auth.before_request
5
def before_request():
6
try:
7
g.user = psg.authenticateRequest(request)
8
except PassageError as e:
9
# unauthorized
10
return render_template('unauthorized.html')
11
12
@auth.route('/authenticated', methods=['GET'])
13
def auth():
14
# g.user will be set to the passage user id here
15
# ... add logic here ...
Copied!

Creating Users in Your Database

When users register for your application, Passage will create an account for them. You can choose to just use the middleware above and access user data on demand from Passage.
More likely, you will will want a record of the user in your database when they are created so that you can reference a Passage user by ID at any time. Let's say you have a database model that looks like this, where a user has a "name" field and a "passage_id" field that corresponds to their Passage ID.
1
class User(db.Model):
2
id = db.Column(db.Integer, primary_key = True)
3
name = db.Column(db.String(100))
4
passage_id = db.Column(db.String(32), primary_key = True)
Copied!
You will then add a createUser endpoint that will add a user to your database.
1
auth.route('/user', methods=['POST'])
2
def createUser():
3
# g.user will be set to the Passage user id
4
u = User()
5
u.passage_id = g.user
6
​
7
# commit to database
8
db.session.add(u)
9
db.session.commit()
10
​
11
return jsonify({"result": 200})
Copied!
Then create an onSuccess callback on your Passage Register element that will send user data to the above endpoint once a user has been created successfully. Add the following code to a script tag just after the Passage Register element.
1
<passage-register app-id="{{psg_app_id}}"></passage-register>
2
<script src="https://cdn.passage.id/passage-web.js"></script>
3
<script>
4
const onSuccess = (authResult) =>{
5
document.cookie = "psg_auth_token=" + authResult.authToken + ";path=/";
6
const urlParams = new URLSearchParams(window.location.search)
7
const magicLink = urlParams.has('psg_magic_link') ? urlParams.get('psg_magic_link') : null
8
if (magicLink !== null) {
9
new Promise((resolve) => {
10
setTimeout(resolve, 3000)
11
}).then( ()=>{ window.location.href = authResult.redirectURL;})
12
return;
13
}
14
$.ajax({
15
type: "POST",
16
async: false,
17
url: "{{api_url}}/user",
18
data: JSON.stringify({}), // could include other data here
19
contentType: "application/json",
20
dataType: 'json'
21
});
22
window.location.href = authResult.redirectURL;
23
}
24
</script>
Copied!
A common use case for this is customizing registration data, which you can find an example of here.

Accessing User Data

In any functions that use the Passage middleware above, you can use the Passage User ID to refer to the user. We recommend storing the Passage User ID in your own users table to be able to reference at any time. You can use the user ID to get and update user information (e.g. email address) from your application.
An example User model might look like this, where a user has a "name" field and a "passage_id" field that corresponds to their Passage ID.
1
class User(db.Model):
2
id = db.Column(db.Integer, primary_key=True)
3
name = db.Column(db.String(100))
4
passage_id = db.Column(db.String(24), index=True)
Copied!
To access data about a user, you can query the User table by passage_id in any route that is authenticated with Passage and you can use the Passage SDK to query for any Passage-specific user data (like email address or phone number).
1
@auth.route('/dashboard', methods=['GET'])
2
def dashboard():
3
# g.user should be set here to the Passage user ID
4
​
5
# use Passage user ID to get user record in DB
6
user = User.query.filter_by(passage_id=g.user).first()
7
​
8
# use Passage SDK to get info stored in Passage (email)
9
psg_user = psg.getUser(g.user)
10
​
11
return render_template('dashboard.html', name=user.name, email=psg_user.email
Copied!
​
​