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:
The id of the user
A map from OrgID to OrgMemberInfoFromToken
The original ID of the user, if the user was migrated from an external source
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)
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)
The minimum role of the user.
HasPermission
Returns true if the user has the exact permission.
orgMemberInfo.HasPermission(permission)
The exact permission of the user.
HasAllPermissions
returns true if the user has all of the permissions.
orgMemberInfo.HasAllPermissions(permissions)
The permissions of the user.
Fetching functions
Fetch user metadata by id
client.FetchUserMetadataByUserID(userId, includeOrgs)
Parameters
The id of the user
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
The email of the user
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
The username of the user
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)
The array of user Ids
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)
The array of user emails
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)
The array of user usernames
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)
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)
The org ID
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)
The org ID
Fetch all organizations
client.FetchOrgByQuery(OrgQuery)
User Management
Create User
client.CreateUser(CreateUserQuery)
Update User Email
client.UpdateUserEmail(userId, UpdateEmailQuery)
The id of the user
Update User Metadata
client.UpdateUserMetadata(userId, UpdateUserMetadataQuery)
The id of the user
Update User Password
client.UpdateUserPassword(userId, UpdateUserPasswordQuery)
The id of the user
Clear User Password
client.ClearUserPassword(userId)
The id of the user
Disable 2FA
client.DisableUser2fa(userId)
The id of the user
Delete user
client.DeleteUser(userId)
The id of the user
Disable user
client.DisableUser(userId)
The id of the user
Enable user
client.EnableUser(userId)
The id of the user
Migrate User from External Source
client.MigrateUserFromExternalSource(MigrateUserQuery)
Create magic link
client.CreateMagicLink(CreateMagicLinkQuery)
Create Access Token
client.CreateAccessToken(userId, durationInMinutes)
The id of the user
The duration of the access token, in minutes
Org Management
Create Organization
client.CreateOrg(name)
The organization’s name
Add user to organization
client.AddUserToOrg(AddUserToOrgQuery)
Create organization V2
client.CreateOrgV2(CreateOrgV2Query)
Add user to organization
client.AddUserToOrg(AddUserToOrgQuery)
Change user role within organization
client.ChangeUserRoleInOrg(ChangeUserRoleInOrgQuery)
Remove user From organization
client.RemoveUserFromOrg(RemoveUserFromOrgQuery)
Allow organization to set up SAML connection
client.AllowOrgToSetupSamlConnection(orgId)
The id of the organization
Disallow organization to set up SAML connection
client.DisallowOrgToSetupSamlConnection(orgId)
The id of the organization
Update organization Metadata
client.UpdateOrgMetadata(orgId, UpdateOrgQuery)
The id of the organization
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)
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)
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)
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)
The API Key id
Fetch Current API Keys
client.FetchCurrentAPIKeys(APIKeysQuery)
Fetch Archived API Keys
client.FetchArchivedAPIKeys(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)
Update API Key
client.UpdateAPIKey(apiKeyID, APIKeyCreateParams)
The API Key id
Delete API Key
client.DeleteAPIKey(apiKeyID)
The API Key id