Get User Info
There are several ways to fetch information about a user:
- Using their user ID, you can get their email ID, time joined, and metadata that is saved in the user metadata recipe.
- If the user logged in via a third party providers, you can get their profile info in the post sign up override along with the provider's access token. You can save this information in the user metadata recipe for later retrieval.
- Lastly, you can get the user's session information and access token payload from their session handle (offline mode), or from the currently logged in session object (online mode).
#
Fetching information using the user's email- NodeJS
- GoLang
- Python
You can get a user's information on the backend using the getUsersByEmail
, getUserByPhoneNumber
and getUserById
functions:
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
async function handler() { const userInfo = await ThirdPartyPasswordless.getUsersByEmail("test@example.com");}
You can get a user's information on the backend using the GetUserByEmail
, GetUserByPhoneNumber
and GetUserById
functions:
import ( "fmt"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless")
func main() {
userInfo, err := thirdpartypasswordless.GetUsersByEmail("test@example.com") if err != nil { // TODO: Handle error return } fmt.Println(userInfo) //...}
- Asyncio
- Syncio
from supertokens_python.recipe.thirdpartypasswordless.asyncio import get_users_by_email
async def some_func(): _ = await get_users_by_email("test@example.com")
from supertokens_python.recipe.thirdpartypasswordless.syncio import get_users_by_email
user_info = get_users_by_email("test@example.com")
#
Fetching information using the user's phone number- NodeJS
- GoLang
- Python
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";
async function handler() { const userInfo = await ThirdPartyPasswordless.getUserByPhoneNumber({phoneNumber: "+1234567891"});}
import ( "fmt"
"github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless")
func main() {
userInfo, err := thirdpartypasswordless.GetUserByPhoneNumber("+1234567890") if err != nil { // TODO: Handle error return } fmt.Println(userInfo) //...}
- Asyncio
- Syncio
from supertokens_python.recipe.thirdpartypasswordless.asyncio import get_user_by_phone_number
async def some_func(): _ = await get_user_by_phone_number("+1234567890")
from supertokens_python.recipe.thirdpartypasswordless.syncio import get_user_by_phone_number
user_info = get_user_by_phone_number("+1234567890")
#
Fetching information using the user's IDgetUserById
function#
Using the - NodeJS
- GoLang
- Python
- Express
- Hapi
- Fastify
- Koa
- Loopback
- AWS Lambda / Netlify
- Next.js
- NestJS
import express from "express";import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";import { verifySession } from "supertokens-node/recipe/session/framework/express";import { SessionRequest } from 'supertokens-node/framework/express';
let app = express();app.get("/get-user-info", verifySession(), async (req: SessionRequest, res) => { let userId = req.session!.getUserId(); // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki let userInfo = await ThirdPartyPasswordless.getUserById(userId) // ... })
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";import { verifySession } from "supertokens-node/recipe/session/framework/hapi";import Hapi from "@hapi/hapi";import { SessionRequest } from "supertokens-node/framework/hapi";
let server = Hapi.server({ port: 8000 });
server.route({ path: "/get-user-info", method: "get", options: { pre: [ { method: verifySession() }, ], }, handler: async (req: SessionRequest, res) => { let userId = req.session!.getUserId(); // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki let userInfo = await ThirdPartyPasswordless.getUserById(userId); //... }})
import Fastify from "fastify";import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";import { verifySession } from "supertokens-node/recipe/session/framework/fastify";import { SessionRequest } from 'supertokens-node/framework/fastify';
const fastify = Fastify();
fastify.post("/like-comment", { preHandler: verifySession(),}, async (req: SessionRequest, res) => { let userId = req.session!.getUserId(); // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki let userInfo = await ThirdPartyPasswordless.getUserById(userId); //....});
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";import { verifySession } from "supertokens-node/recipe/session/framework/awsLambda";import { SessionEvent } from "supertokens-node/framework/awsLambda";
async function getUserInfo(awsEvent: SessionEvent) { let userId = awsEvent.session!.getUserId(); // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki let userInfo = await ThirdPartyPasswordless.getUserById(userId); //....};
exports.handler = verifySession(getUserInfo);
import KoaRouter from "koa-router";import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";import { verifySession } from "supertokens-node/recipe/session/framework/koa";import { SessionContext } from "supertokens-node/framework/koa";
let router = new KoaRouter();
router.get("/get-user-info", verifySession(), async (ctx: SessionContext, next) => { let userId = ctx.session!.getUserId(); // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki let userInfo = await ThirdPartyPasswordless.getUserById(userId); //....});
import { inject, intercept } from "@loopback/core";import { RestBindings, MiddlewareContext, get, response } from "@loopback/rest";import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";import { verifySession } from "supertokens-node/recipe/session/framework/loopback";import Session from "supertokens-node/recipe/session";import { SessionContext } from "supertokens-node/framework/loopback";
class GetUserInfo { constructor(@inject(RestBindings.Http.CONTEXT) private ctx: MiddlewareContext) {} @get("/get-user-info") @intercept(verifySession()) @response(200) async handler() { let userId = ((this.ctx as any).session as Session.SessionContainer).getUserId(); // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki let userInfo = await ThirdPartyPasswordless.getUserById(userId); //.... }}
import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";import { superTokensNextWrapper } from 'supertokens-node/nextjs'import { verifySession } from "supertokens-node/recipe/session/framework/express";import { SessionRequest } from "supertokens-node/framework/express";
export default async function likeComment(req: SessionRequest, res: any) { await superTokensNextWrapper( async (next) => { await verifySession()(req, res, next); }, req, res )
let userId = req.session!.getUserId(); // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki let userInfo = await ThirdPartyPasswordless.getUserById(userId); //....}
import { Controller, Post, UseGuards, Request, Response } from "@nestjs/common";import { AuthGuard } from './auth/auth.guard';import { Session } from './auth/session.decorator';import ThirdPartyPasswordless from "supertokens-node/recipe/thirdpartypasswordless";import { SessionRequest } from "supertokens-node/framework/express";
@Controller()export class ExampleController { @Post('example') @UseGuards(new AuthGuard()) // For more information about this guard please read our NestJS guide. async postExample(@Request() req: SessionRequest, @Session() session: Session, @Response({passthrough: true}) res: Response): Promise<boolean> { let userId = session.getUserId(); // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki let userInfo = await ThirdPartyPasswordless.getUserById(userId); //.... return true; }}
- Chi
- net/http
- Gin
- Mux
import ( "fmt" "net/http"
"github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless")
func main() { _ = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { session.VerifySession(nil, getUserInfoAPI).ServeHTTP(rw, r) })}
func getUserInfoAPI(w http.ResponseWriter, r *http.Request) { sessionContainer := session.GetSessionFromRequestContext(r.Context())
userID := sessionContainer.GetUserID() // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki userInfo, err := thirdpartypasswordless.GetUserById(userID) if err != nil { // TODO: Handle error return } fmt.Println(userInfo)}
import ( "fmt" "net/http"
"github.com/gin-gonic/gin" "github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/recipe/session/sessmodels" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless")
func main() { router := gin.New() router.GET("/getuserinfo", verifySession(nil), getUserInfoAPI)}
func verifySession(options *sessmodels.VerifySessionOptions) gin.HandlerFunc { return func(c *gin.Context) { session.VerifySession(options, func(rw http.ResponseWriter, r *http.Request) { c.Request = c.Request.WithContext(r.Context()) c.Next() })(c.Writer, c.Request) // we call Abort so that the next handler in the chain is not called, unless we call Next explicitly c.Abort() }}
func getUserInfoAPI(c *gin.Context) { sessionContainer := session.GetSessionFromRequestContext(c.Request.Context())
userID := sessionContainer.GetUserID()
// You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki userInfo, err := thirdpartypasswordless.GetUserById(userID) if err != nil { // TODO: Handle error return } fmt.Println(userInfo) //...}
import ( "fmt" "net/http"
"github.com/go-chi/chi" "github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless")
func main() { r := chi.NewRouter() r.Get("/getuserinfo", session.VerifySession(nil, getUserInfoAPI))}
func getUserInfoAPI(w http.ResponseWriter, r *http.Request) { sessionContainer := session.GetSessionFromRequestContext(r.Context())
userID := sessionContainer.GetUserID() // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki userInfo, err := thirdpartypasswordless.GetUserById(userID) if err != nil { // TODO: Handle error return } fmt.Println(userInfo)}
import ( "fmt" "net/http"
"github.com/gorilla/mux" "github.com/supertokens/supertokens-golang/recipe/session" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless")
func main() { router := mux.NewRouter() router.HandleFunc("/getuserinfo", session.VerifySession(nil, getUserInfoAPI)).Methods(http.MethodGet)}
func getUserInfoAPI(w http.ResponseWriter, r *http.Request) { sessionContainer := session.GetSessionFromRequestContext(r.Context())
userID := sessionContainer.GetUserID() // You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki userInfo, err := thirdpartypasswordless.GetUserById(userID) if err != nil { // TODO: Handle error return } fmt.Println(userInfo)}
- FastAPI
- Flask
- Django
from supertokens_python.recipe.session.framework.fastapi import verify_sessionfrom supertokens_python.recipe.thirdpartypasswordless.asyncio import get_user_by_idfrom supertokens_python.recipe.session import SessionContainerfrom fastapi import FastAPI, Depends
app = FastAPI()
@app.post('/get_user_info_api') async def get_user_info_api(session: SessionContainer = Depends(verify_session())): user_id = session.get_user_id()
# You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki _ = await get_user_by_id(user_id)
from supertokens_python.recipe.session.framework.flask import verify_sessionfrom supertokens_python.recipe.thirdpartypasswordless.syncio import get_user_by_idfrom flask import Flask, gfrom supertokens_python.recipe.session import SessionContainer
app = Flask(__name__)
@app.route('/update-jwt', methods=['POST']) @verify_session()def get_user_info_api(): session: SessionContainer = g.supertokens
user_id = session.get_user_id()
# You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki _ = get_user_by_id(user_id)
from supertokens_python.recipe.session.framework.django.asyncio import verify_sessionfrom supertokens_python.recipe.thirdpartypasswordless.asyncio import get_user_by_idfrom django.http import HttpRequestfrom supertokens_python.recipe.session import SessionContainer
@verify_session()async def get_user_info_api(request: HttpRequest): session: SessionContainer = request.supertokens
user_id = session.get_user_id()
# You can learn more about the `User` object over here https://github.com/supertokens/core-driver-interface/wiki _ = await get_user_by_id(user_id)
#
Using the user metadata recipeCheckout the user metadata recipe docs which shows you how to save and fetch any JSON object against the user's ID. You can use this to save information like the user's name (first_name
and last_name
) or any other field associated with the user.
#
Getting information from the user's sessionThe user's session contains their user ID and the session's payload. You can access this on the backend and frontend as well as whilst the user is online or offline.
More information about this can be found in the session docs.
#
Getting the user's third party provider information and access tokenIf the user used a third party provider to login, you can access their info via SuperTokens as shown below. You can then save the OAuthTokens in your own db or in SuperTokens (using the user metadata recipe) and use them to fetch / change info about the logged in user from the third party provider
- NodeJS
- GoLang
- Python
import SuperTokens from "supertokens-node";import ThirdPartyEmailPassword from "supertokens-node/recipe/thirdpartypasswordless";import Session from "supertokens-node/recipe/session";
SuperTokens.init({ appInfo: { apiDomain: "...", appName: "...", websiteDomain: "..." }, supertokens: { connectionURI: "...", }, recipeList: [ ThirdPartyEmailPassword.init({ override: { functions: (originalImplementation) => { return { ...originalImplementation, // override the thirdparty sign in / up API thirdPartySignInUpPOST: async function(input) { if (originalImplementation.thirdPartySignInUpPOST === undefined) { throw Error("Should never come here"); }
// TODO: Some pre sign in / up logic
let response = await originalImplementation.thirdPartySignInUpPOST(input);
if (response.status === "OK") { if (response.createdNewUser) { // TODO: some post sign up logic } else { // TODO: some post sign in logic } }
return response; } } } } }), Session.init({ /* ... */ }) ]});
import ( "fmt"
"github.com/supertokens/supertokens-golang/recipe/thirdparty/tpmodels" "github.com/supertokens/supertokens-golang/recipe/thirdpartypasswordless" "github.com/supertokens/supertokens-golang/recipe/thirdpartyemailpassword/tpepmodels" "github.com/supertokens/supertokens-golang/supertokens")
func main() {
supertokens.Init(supertokens.TypeInput{ RecipeList: []supertokens.Recipe{ thirdpartyemailpassword.Init(&tpepmodels.TypeInput{ Override: &tpepmodels.OverrideStruct{ Functions: func(originalImplementation tpepmodels.RecipeInterface) tpepmodels.RecipeInterface { originalThirdPartySignInUp := *originalImplementation.ThirdPartySignInUp
// override the thirdparty sign in / up function (*originalImplementation.ThirdPartySignInUp) = func(thirdPartyID, thirdPartyUserID, email string, oAuthTokens tpmodels.TypeOAuthTokens, rawUserInfoFromProvider tpmodels.TypeRawUserInfoFromProvider, userContext supertokens.UserContext) (tpepmodels.SignInUpResponse, error) {
resp, err := originalThirdPartySignInUp(thirdPartyID, thirdPartyUserID, email, oAuthTokens, rawUserInfoFromProvider, userContext) if err != nil { return tpepmodels.SignInUpResponse{}, err }
if resp.OK != nil { user := resp.OK.User fmt.Println(user)
// This is the response from the OAuth tokens provided by the third party provider fmt.Println(resp.OK.OAuthTokens["access_token"]) // other tokens like the refresh_token or id_token are also // available in the OAuthTokens object.
// This gives the user's info as returned by the provider's user profile endpoint. fmt.Println(resp.OK.RawUserInfoFromProvider.FromUserInfoAPI["first_name"])
// This gives the user's info from the returned ID token // if the provider gave us an ID token fmt.Println(resp.OK.RawUserInfoFromProvider.FromIdTokenPayload["first_name"]) }
return resp, err }
return originalImplementation }, }, }), }, })}
from supertokens_python import init, InputAppInfofrom supertokens_python.recipe import thirdpartypasswordlessfrom supertokens_python.recipe.thirdpartyemailpassword.interfaces import APIInterface, ThirdPartyAPIOptions, EmailPasswordAPIOptions, ThirdPartySignInUpPostOkResult, EmailPasswordSignInPostOkResult, EmailPasswordSignUpPostOkResultfrom typing import Union, Dict, Any, Listfrom supertokens_python.recipe.thirdparty.provider import Providerfrom supertokens_python.recipe.emailpassword.types import FormField
def override_thirdpartyemailpassword_apis(original_implementation: APIInterface): original_thirdparty_sign_in_up_post = original_implementation.thirdparty_sign_in_up_post async def thirdparty_sign_in_up_post(provider: Provider, code: str, redirect_uri: str, client_id: Union[str, None], auth_code_response: Union[Dict[str, Any], None], api_options: ThirdPartyAPIOptions, user_context: Dict[str, Any]): # call the default behaviour as show below result = await original_thirdparty_sign_in_up_post(provider, code, redirect_uri, client_id, auth_code_response, api_options, user_context) if isinstance(result, ThirdPartySignInUpPostOkResult): if result.created_new_user: pass # TODO: some post sign up logic else: pass # TODO: some post sign in logic return result
original_implementation.thirdparty_sign_in_up_post = thirdparty_sign_in_up_post return original_implementation
init( app_info=InputAppInfo(api_domain="...", app_name="...", website_domain="..."), framework='...', recipe_list=[ thirdpartyemailpassword.init( override=thirdpartyemailpassword.InputOverrideConfig( functions=override_thirdpartyemailpassword_apis ) ) ])