Go Reference

PropelAuth's Go library provides all the building blocks you need to add authentication to your Go projects.

Installation

go get github.com/propelauth/propelauth-go

Initialize

To initialize the library, you call propelauth.InitBaseAuth with the configuration for your application:

import (
    "os"
    "fmt"
    propelauth "github.com/propelauth/propelauth-go/pkg"
    models "github.com/propelauth/propelauth-go/pkg/models"
)

func main() {
    // initialize the client

    // (you can get these variables from the Backend Integrations section on your dashboard)
    apiKey := os.Getenv("PROPELAUTH_API_KEY")
    authUrl := os.Getenv("PROPELAUTH_AUTH_URL")

    client, err := propelauth.InitBaseAuth(authUrl, apiKey, nil)
    if err != nil {
        panic(err)
    }
    // ...
}

This will fetch the information needed to validate access tokens. In a serverless environment, you may want to skip this one-time fetch, and you can do so by passing in the TokenVerificationMetadataInput object:

client, err := propelauth.InitBaseAuth(authUrl, apiKey, &propelauth.TokenVerificationMetadataInput{
    // (you can get these variables from the Backend Integrations section on your dashboard)
    VerifierKey: os.Getenv("PROPELAUTH_VERIFIER_KEY"),
    Issuer: os.Getenv("PROPELAUTH_ISSUER"),
})

Protect API Routes

After initializing auth, you can verify access tokens by passing in the Authorization header (formatted Bearer TOKEN), see User for more information:

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 this:

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))

Authorization / Organizations

You can also verify which organizations the user is in, and which roles and permissions they have, with the GetOrgMemberInfo function on the user object:

orgMemberInfo, err := user.GetOrgMemberInfo(orgId)
if err != nil {
        w.WriteHeader(403)
        return
}
if !orgMemberInfo.IsRole("Admin") {
        w.WriteHeader(403)
        return
}

User

The User object contains information about the user that made the request.

  • Name
    UserID
    Type
    uuid.UUID
    Description

    The unique id of the user.

  • Name
    Email
    Type
    string
    Description

    The email of the user.

  • Name
    FirstName
    Type
    string
    Description

    The first name of the user.

  • Name
    LastName
    Type
    string
    Description

    The last name of the user.

  • Name
    Username
    Type
    string
    Description

    The username of the user.

  • Name
    LegacyUserID
    Type
    string
    Description

    If the user was migrated using our Migration API, this will be the id of the user in the legacy system.

  • Name
    ImpersonatorUserID
    Type
    string
    Description

    If the user is being impersonated, this is id of the user that impersonated them.

  • Name
    ActiveOrgId
    Type
    string | undefined
    Description

    The ID of the Active Org.

  • Name
    LoginMethod
    Type
    object
    Description

    The method the user used to log in. Returns the Login Method Property.

  • Name
    Properties
    Type
    *map[string]interface{}
    Description

    A dictionary of custom properties associated with the user.

  • Name
    GetOrgMemberInfo
    Type
    fn(org_id: string) -> *OrgMemberInfoFromToken
    Description

    A function that returns information about the user's membership in the specified organization.

  • Name
    GetActiveOrgMemberInfo
    Type
    fn() => OrgMemberInfoFromToken
    Description

    Returns the OrgMemberInfo of the Active Org.

  • Name
    OrgIdToOrgMemberInfo
    Type
    map[string]*OrgMemberInfoFromToken
    Description

    A dictionary mapping from organization id to OrgMemberInfo object.


OrgMemberInfo

The OrgMemberInfo object contains information about the user's membership in an organization.

  • Name
    OrgID
    Type
    uuid.UUID
    Description

    The unique id of the organization.

  • Name
    OrgName
    Type
    string
    Description

    The name of the organization.

  • Name
    OrgMetadata
    Type
    map[string]interface{}
    Description

    The metadata associated with the organization.

  • Name
    UserAssignedRole
    Type
    string
    Description

    The role of the user in the organization.

  • Name
    UserInheritedRolesPlusCurrentRole
    Type
    []string
    Description

    The role of the user within this organization plus each inherited role.

  • Name
    UserPermissions
    Type
    []string
    Description

    A list of permissions the user has in the organization, based on their role.

  • Name
    IsRole
    Type
    fn(role: string) -> bool
    Description

    A function that returns true if the user has the specified role in the organization.

  • Name
    IsAtLeastRole
    Type
    fn(role: string) -> bool
    Description

    A function that returns true if the user has at least the specified role in the organization.

  • Name
    HasPermission
    Type
    fn(permission: string) -> bool
    Description

    A function that returns true if the user has the specified permission in the organization.

  • Name
    HasAllPermissions
    Type
    fn(permissions: list[string]) -> bool
    Description

    A function that returns true if the user has all of the specified permissions in the organization.

  • Name
    OrgRoleStructure
    Type
    string
    Description

    The role structure set for your project. See single and multi role per user for more information.

  • Name
    UserAssignedAdditionalRoles
    Type
    []string
    Description

    If using multiple roles per user, returns an array of roles that the user belongs to. Excludes the UserAssignedRole.


Calling Backend APIs

You can also use the library to call the PropelAuth APIs directly, allowing you to fetch users, create orgs, and a lot more.

response, err := auth.CreateMagicLink(models.CreateMagicLinkParams{
    Email: "test@example.com",
})

See the API Reference for more information.