# Go Reference

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

## [Installation](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#installation)

```shell
go get github.com/propelauth/propelauth-go
```

---

## [Initialize](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#initialize)

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

```go
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:

```go
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](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#protect-api-routes)

After initializing auth, you can verify access tokens by passing in the Authorization header (formatted `Bearer TOKEN`), see [User](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#user) for more information:

```go
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:

```go
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:

```go
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](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#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](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#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](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#user) object.

```go
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](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#org-member-info) 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.

```go
// 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](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#org-member-info) 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.

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

## [User](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#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](https://docs.propelauth.com/migrations), 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](https://docs.propelauth.com/recipes/active-org).
- Name `LoginMethod`  Type object  Description The method the user used to log in. Returns the [Login Method Property](https://docs.propelauth.com/overview/authentication/login-methods).
- Name `Properties`  Type *map[string]interface{}  Description A dictionary of [custom properties](https://docs.propelauth.com/overview/user-management/user-properties#custom-user-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](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#org-member-info) of the [Active Org](https://docs.propelauth.com/recipes/active-org).
- Name `OrgIdToOrgMemberInfo`  Type map[string]*OrgMemberInfoFromToken  Description A dictionary mapping from organization id to [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#org-member-info) object.

---

## [OrgMemberInfo](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#org-member-info)

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 [multis role per user](https://docs.propelauth.com/overview/authorization/managing-roles-permissions#multiple-roles-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](https://docs.propelauth.com/reference/backend-apis/go?ref=propelauth.mymidnight.blog#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.

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

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

See the [API Reference](https://docs.propelauth.com/reference) for more information.
