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.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.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.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"}
    },
    Properties: map[string]interface{}{"custom_property": "custom_value"},
}

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
[]uuid.UUID

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
uuid.UUID

The id of the user

UpdateEmailQuery

Update User Metadata

client.UpdateUserMetadata(userId, UpdateUserMetadataQuery)
userId
uuid.UUID

The id of the user

UserMetadata

Update User Password

client.UpdateUserPassword(userId, UpdateUserPasswordQuery)
userId
uuid.UUID

The id of the user

UserMetadata

Clear User Password

client.ClearUserPassword(userId)
userId
uuid.UUID

The id of the user

Disable 2FA

client.DisableUser2fa(userId)
userId
uuid.UUID

The id of the user

Delete user

client.DeleteUser(userId)
userId
uuid.UUID

The id of the user

Disable user

client.DisableUser(userId)
userId
uuid.UUID

The id of the user

Enable user

client.EnableUser(userId)
userId
uuid.UUID

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
uuid.UUID

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

Create organization V2

client.CreateOrgV2(CreateOrgV2Query)
CreateOrgV2Query

Add user to organization

client.AddUserToOrg(AddUserToOrgQuery)
AddUserToOrgQuery

Change user role within organization

client.ChangeUserRoleInOrg(ChangeUserRoleInOrgQuery)
ChangeUserRoleInOrgQuery

Remove user From organization

client.RemoveUserFromOrg(RemoveUserFromOrgQuery)
ChangeUserRoleInOrgQuery

Allow organization to set up SAML connection

client.AllowOrgToSetupSamlConnection(orgId)
orgId
uuid.UUID

The id of the organization

Disallow organization to set up SAML connection

client.DisallowOrgToSetupSamlConnection(orgId)
orgId
uuid.UUID

The id of the organization

Update organization Metadata

client.UpdateOrgMetadata(orgId, UpdateOrgQuery)
orgId
uuid.UUID

The id of the organization

UpdateOrgQuery

API Key Authentication

For more information on API Key Authentication, please refer to our Quickstart Guide on the topic.

Validate Personal API Key

client.ValidatePersonalApiKey(apiKeyToken)
apiKeyToken
string

The API Key token that was issued to the user, or generated by the Create API Key endpoint.

If the token provided is not valid, an error is returned. If the token is valid, a user object that is associated with the token is returned.

Successful response user property contains the same fields as Fetch user metadata by id.

Successful Response

{
   "user":{
      "user_id":"98cef184-7c15-45c5-8918-8c2295aa7ffe",
      "email":"test@propelauth.com",
      //...
   },
    metadata: {}
}

Validate Organization API Key

client.ValidateOrgApiKey(apiKeyToken)
apiKeyToken
string

The API Key token that was issued to the organization, or generated by the Create API Key endpoint.

If the token provided is not valid, an error is returned. If the token is valid, an organization object that is associated with the token is returned.

In addition to validating the API Key, this also makes sure it’s specifically an organization API key.

Successful response contains the same fields as Fetch user metadata by id.

Validate API Key

client.ValidateApiKey(apiKeyToken)
apiKeyToken
string

The API Key token that was issued to the user or organization, or generated by the Create API Key endpoint.

Returns a full user or organization object, depending on where the API Token was issued.

Successful response contains the same fields as Fetch user metadata by id.

Fetch API Key

client.FetchAPIKey(apiKeyID)
apiKeyID
string

The API Key id

Fetch Current API Keys

client.FetchCurrentAPIKeys(APIKeysQuery)
APIKeysQuery

Fetch Archived API Keys

client.FetchArchivedAPIKeys(APIKeysQuery)
APIKeysQuery

Create API Key

Note: We have hosted pages for users to create API Keys. However, if you would like to do this programmatically, we have provided this endpoint to create keys via your backend.

client.CreateAPIKey(APIKeyCreateParams)
APIKeyCreateParams

Update API Key

client.UpdateAPIKey(apiKeyID, APIKeyCreateParams)
apiKeyID
string

The API Key id

APIKeyUpdateParams

Delete API Key

client.DeleteAPIKey(apiKeyID)
apiKeyID
string

The API Key id