Go Reference - PropelAuth Docs

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
}

Verifying the access token doesn't require an external request.

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.

Check Org Membership

Verify that the request was made by a valid user and that the user is a member of the specified organization. This can be done using the User object.

orgMemberInfo := user.GetOrgMemberInfo(orgId)
if orgMemberInfo == nil {
        w.WriteHeader(403)
        return
}

Check Org Membership and Role

Similar to checking org membership, but will also verify that the user has a specific Role in the organization. This can be done using the OrgMemberInfo object.

A user has a Role within an organization. By default, the available roles are Owner, Admin, or Member, but these can be configured. These roles are also hierarchical, so Owner > Admin > Member.

// Assuming a Role structure of Owner => Admin => Member

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

Check Org Membership and Permission

Similar to checking org membership, but will also verify that the user has the specified permission in the organization. This can be done using the OrgMemberInfo object.

Permissions are arbitrary strings associated with a role. For example, can_view_billing, ProductA::CanCreate, and ReadOnly are all valid permissions. You can create these permissions in the PropelAuth dashboard.

orgMemberInfo := user.GetOrgMemberInfo(orgId)
if orgMemberInfo == nil {
        w.WriteHeader(403)
        return
}
if !orgMemberInfo.HasPermission("can_view_billing") {
        w.WriteHeader(403)
        return
}

User

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


OrgMemberInfo

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


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.

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

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

See the API Reference for more information.