Backend
Go Library Reference

PropelAuth’s Go library provides all the building blocks you need to add authentication to any Go backend.

Installation

go get github.com/propelauth/propelauth-go

Initialize

propelauth.InitBaseAuth performs a one-time initialization of the library. It will verify your apiKey is correct and fetch the metadata needed to verify requests sent from the frontend. You can find the authUrl and apiKey in the PropelAuth dashboard under Backend Integration. We recommend storing them in environment variables as you will have different values for each environment.

client, err := propelauth.InitBaseAuth(authUrl, apiKey, nil)

Protect API Routes

You can protect an API route by validating the Authorization header:

user, err := client.GetUser(r.Header.Get("Authorization"))
if err != nil {
    w.WriteHeader(401)
    return
}

Here’s an example where we create an auth middleware that will protect a route and set the user on the request context:

func requireUser(client *propelauth.Client, next http.HandlerFunc) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := client.GetUser(r.Header.Get("Authorization"))
		if err != nil {
				w.WriteHeader(401)
				return
		}
		requestContext := context.WithValue(r.Context(), "user", user)
		next.ServeHTTP(w, r.WithContext(requestContext))
	})
}

Which can then be used like:

func whoami(w http.ResponseWriter, req *http.Request) {
	user := req.Context().Value("user").(*models.UserFromToken)
	json.NewEncoder(w).Encode(user)
}
// ...
http.Handle("/api/whoami", requireUser(client, whoami))

Roles and Permissions

In the Protect API Routes section, we created an auth middleware that protected a route and set the user on the request context. To expand, here is an example of authorization using the default Go http module, using the built in GetOrgMemberInfo and IsRole functions to determine if the user is an admin.

func requireAdmin(client *propelauth.Client, next http.HandlerFunc) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := client.GetUser(r.Header.Get("Authorization"))
		if err != nil {
				w.WriteHeader(401)
				return
		}
		// Get the org id from the request - this could be a path param, header, query param
		orgId := getOrgIdFromRequest(r)
		orgMemberInfo, err := user.GetOrgMemberInfo(orgId)
		if err != nil {
				w.WriteHeader(403)
				return
		}
		if !orgMemberInfo.IsRole("Admin") {
				w.WriteHeader(403)
				return
		}
		requestContext := context.WithValue(r.Context(), "user", user)
		requestContext = context.WithValue(requestContext, "orgMemberInfo", orgMemberInfo)
		next.ServeHTTP(w, r.WithContext(requestContext))
	})
}

The user object contains:

UserID
UUID

The id of the user

OrgIDToOrgMemberInfo
map[string]*OrgMemberInfoFromToken

A map from OrgID to OrgMemberInfoFromToken

LegacyUserID
*string

The original ID of the user, if the user was migrated from an external source

ImpersonatorUserID
*UUID

If someone on your team is impersonating another user, this will be set to the employee’s ID. By default, user impersonation is turned off and this will be nil

There are also additional authorization functions that exist on the OrgIDToOrgMemberInfo object:

IsRole

Returns true if the user has the exact role.

orgMemberInfo.IsRole(exactRole)
exactRole
string

The exact role of the user.

IsAtLeastRole

Returns true if the user has the exact role or a role that is higher in the hierarchy.

orgMemberInfo.IsAtLeastRole(minimumRole)
minimumRole
string

The minimum role of the user.

HasPermission

Returns true if the user has the exact permission.

orgMemberInfo.HasPermission(permission)
permission
string

The exact permission of the user.

HasAllPermissions

returns true if the user has all of the permissions.

orgMemberInfo.HasAllPermissions(permissions)
permissions
[]string

The permissions of the user.

Fetching functions

Fetch user metadata by id

client.FetchUserMetadataByUserID(userId, includeOrgs)

Parameters

userId
UUID

The id of the user

includeOrgs
bool

Whether to return organization information

Successful response:

models.UserMetadata{
    UserID: uuid.MustParse("e08aa7f2-b2d8-4ad2-9fda-1cda86a9f533"),
    Email: "user@example.com",
    EmailConfirmed: true,
    HasPassword: true,
    Username: "example_username",
    FirstName: "Firstname",
    LastName: "LastName",
    PictureURL: "https://img.propelauth.com/2a27d237-db8c-4f82-84fb-5824dfaedc87.png",
    Locked: false,
    Enabled: true,
    MFAEnabled: false,
    CreatedAt: 1680895145,
    LastActiveAt: 1682024563,
    LegacyUserID: "",
    OrgIDToOrgInfo: map[UUID]models.OrgInfo{UUID.Must"c784285e-d827-4801-9362-1f1361e20329":
        models.OrgInfo{OrgID:UUID.Must"c784285e-d827-4801-9362-1f1361e20329", OrgName:"Acme", UserRole:"Owner"}
    }
}

Fetch user metadata by email

client.FetchUserMetadataByEmail(email, includeOrgs)

Parameters

email
string

The email of the user

includeOrgs
boolean

Whether to return organization information

Successful response is the same as Fetch user metadata by id.

Fetch user metadata by username

client.FetchUserMetadataByUsername(username, includeOrgs)

Parameters

username
string

The username of the user

includeOrgs
boolean

Whether to return organization information

Successful response is the same as Fetch user metadata by id.

Batch fetch users by ids

client.FetchBatchUserMetadataByUserIds(userIds, includeOrgs)
userIds
[]string

The array of user Ids

includeOrgs
boolean

Whether to return organization information

A successful response will be a map of the user objects set to keys of the userIds you passed in. For example:

map[UUID]models.UserMetadata{
    UUID.MustParse("e08aa7f2-b2d8-4ad2-9fda-1cda86a9f533"): models.UserMetadata{
        UserID: uuid.MustParse("e08aa7f2-b2d8-4ad2-9fda-1cda86a9f533"),
        Email: "user@example.com",
        // etc
    },
}

To see the values in the map, see Fetch user metadata by id.

Batch fetch users by emails

client.FetchBatchUserMetadataByEmails(emails, includeOrgs)
emails
[]string

The array of user emails

includeOrgs
boolean

Whether to return organization information

Successful response is the same as Batch fetch users by ids, but the keys are matching email addresses.

Batch fetch users by usernames

client.FetchBatchUserMetadataByUsernames(usernames, includeOrgs)
usernames
[]string

The array of user usernames

includeOrgs
boolean

Whether to return organization information

Successful response is the same as Batch fetch users by ids, but the keys are matching usernames.

Search for users

client.FetchUsersByQuery(UserQuery)
UserQuery

Successful response:

&models.UserList{
    TotalUsers: 45,
    CurrentPage: 0,
    PageSize: 10,
    HasMoreResults: true,
    Users: []models.UserMetadata{
        // See Fetch user metadata by id for the fields
        models.UserMetadata{},
        models.UserMetadata{},
        // ...
    }
}

Fetch users in organization

client.FetchUsersInOrg(orgId, UserInOrgQuery)
orgId
UUID

The org ID

UserInOrgQuery

Successful response:

&models.UserList{
    TotalUsers: 45,
    CurrentPage: 0,
    PageSize: 10,
    HasMoreResults: true,
    Users: []models.UserMetadata{
        // See Fetch user metadata by id for the fields
        models.UserMetadata{},
        models.UserMetadata{},
        // ...
    }
}

Fetch an organization

client.FetchOrg(orgId)
orgId
UUID

The org ID

Fetch all organizations

client.FetchOrgByQuery(OrgQuery)
OrgQuery

User Management

Create User

client.CreateUser(CreateUserQuery)
CreateUserQuery

Update User Email

client.UpdateUserEmail(userId, UpdateEmailQuery)
userId
string

The id of the user

UpdateEmailQuery

Update User Metadata

client.UpdateUserMetadata(userId, UpdateUserMetadataQuery)
userId
string

The id of the user

UserMetadata

Update User Password

client.UpdateUserPassword(userId, UpdateUserPasswordQuery)
userId
string

The id of the user

UserMetadata

Delete user

client.DeleteUser(userId)
userId
string

The id of the user

Disable user

client.DisableUser(userId)
userId
string

The id of the user

Enable user

client.EnableUser(userId)
userId
string

The id of the user

Migrate User from External Source

client.MigrateUserFromExternalSource(MigrateUserQuery)
MigrateUserQuery
client.CreateMagicLink(CreateMagicLinkQuery)
CreateMagicLinkQuery

Create Access Token

client.CreateAccessToken(userId, durationInMinutes)
userId
string

The id of the user

durationInMinutes
int

The duration of the access token, in minutes

Org Management

Create Organization

client.CreateOrg(name)
name
string

The organization’s name

Add user to organization

client.AddUserToOrg(AddUserToOrgQuery)
AddUserToOrgQuery

Allow organization to set up SAML connection

client.AllowOrgToSetupSamlConnection(orgId)
orgId
string

The id of the organization

Disallow organization to set up SAML connection

client.DisallowOrgToSetupSamlConnection(orgId)
orgId
string

The id of the organization

Update Organization Metadata

client.UpdateOrgMetadata(orgId, UpdateOrgQuery)
orgId
string

The id of the organization

UpdateOrgQuery