api

package
v0.0.0-...-9d9692a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 4, 2023 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const BCryptCost = 12

BCryptCost is the cost used for bcrypt password hashing.

View Source
const PageSize = 10

PageSize is the default number of items limit to a page.

View Source
const ScountSchema = "/schema/Scount.json"

ScountSchema is the location for `Scount` JSON schema.

View Source
const UserSchema = "/schema/User.json"

UserSchema is the location for `User` JSON schema.

Variables

View Source
var (
	BodyKey     internal.BodyKey
	AuthUserKey internal.AuthUserKey
	UserKey     internal.UserKey
	QueryKey    internal.QueryKey
	ScountKey   internal.ScountKey
)

Context keys used for passing data across middlewares.

View Source
var DefaultPaginator, _ = ParsePaginator(nil)

DefaultPaginator is a paginator with default values.

View Source
var ErrPaginator = errors.New("invalid pagination parameter")

ErrPaginator defines parsing error for Paginator.

View Source
var ErrUserQuery = errors.New("invalid user query parameters")

ErrUserQuery defines parsing errors for UserQuery.

View Source
var UserSorter = []db.Sorter{
	{
		Column: "uid",
	},
}

UserSorter is the default sort order for user queries.

Functions

func Authware

func Authware(next http.Handler) http.Handler

Authware is the middleware for handling user authentication by validation of auth token in `Authorization` header.

func BodyParser

func BodyParser[T any](next http.Handler) http.Handler

BodyParser is a generic json body parser. Parsed body is stored in context with key BodyKey.

func GenerateID

func GenerateID() string

GenerateID generates cryptographically secure id for entities involved in the application. (10 byte base32)

func GenerateToken

func GenerateToken(subject string) ([]byte, error)

GenerateToken constructs JWT with given subject and signs it with given key. Token is set to an expiry time of 1 hour.

func GetKey

func GetKey() []byte

GetKey obtains the secret key used for JWT signing and verify. The returned byte slice is supposed to be read-only, may not be modified in any way.

func LinkHeader

func LinkHeader(w http.ResponseWriter, links []WebLink)

LinkHeader sets HTTP `Link` header using a list of WebLink.

func ScountPathWare

func ScountPathWare(next http.Handler) http.Handler

ScountPathWare is the middleware to set context key corresponding to "sid" path parameter using ScountKey.

func SetKey

func SetKey(key []byte)

SetKey sets secret key used for JWT signing and verification. Ownership of `key` parameter is passed, so the client may not modify the byte slice.

func Validware

func Validware[T Validator](next http.Handler) http.Handler

Validware is middleware for validation of request body.

Pre-requisite: BodyKey should be present in request context and of type T.

Types

type AuthResource

type AuthResource struct {
	DB *db.Store
}

AuthResource is http.Handler for all requests to `/auth`

func (AuthResource) ChangePassword

func (res AuthResource) ChangePassword(w http.ResponseWriter, r *http.Request)

ChangePassword handles password update requests.

func (AuthResource) LoginUser

func (res AuthResource) LoginUser(w http.ResponseWriter, r *http.Request)

LoginUser handles user sign in.

func (AuthResource) RegisterUser

func (res AuthResource) RegisterUser(w http.ResponseWriter, r *http.Request)

RegisterUser handles user sign up.

func (AuthResource) Router

func (res AuthResource) Router() chi.Router

Router constructs a new chi router for the auth resource.

func (AuthResource) ServeHTTP

func (res AuthResource) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler on AuthResource.

type LoginRequest

type LoginRequest struct {
	// /schema/LoginRequest.json
	// Schema string `json:"$schema,omitempty"`
	Email    string `json:"email"`
	Password string `json:"password"`
}

LoginRequest is the JSON request body format at the `/auth/login` endpoint.

func (LoginRequest) Validate

func (r LoginRequest) Validate() error

Validate implements Validator on LoginRequest. Simply check non-empty.

type LoginResponse

type LoginResponse struct {
	// `/schema/LoginResponse.json`
	Schema string `json:"$schema,omitempty"`
	Token  string `json:"token"`
}

LoginResponse is the JSON response body format at the `/auth/login` endpoint.

type Middleware

type Middleware = func(http.Handler) http.Handler

Middleware is a convenient alias for http middleware.

func QueryParser

func QueryParser[T any](parser func(url.Values) (T, error)) Middleware

QueryParser is a generic url query parser. Parsed query parameters are stored in context with key QueryKey.

type Paginator

type Paginator struct {
	Page int
	Size int
}

Paginator represents the pagination query parameters.

func ParsePaginator

func ParsePaginator(query url.Values) (Paginator, error)

ParsePaginator parses query parameters into Paginator, emitting errors in case of failure.

type PasswordChanger

type PasswordChanger struct {
	// /schema/PasswordChanger.json
	// Schema string `json:"$schema,omitempty"`
	Old string `json:"old"`
	New string `json:"new"`
}

PasswordChanger is the JSON request body format at the `/auth/change` endpoint.

func (PasswordChanger) Validate

func (r PasswordChanger) Validate() error

Validate implements Validator on PasswordChanger. Simply check non-empty.

type RegisterRequest

type RegisterRequest struct {
	// /schema/RegisterRequest.json
	// Schema string `json:"$schema,omitempty"`
	Username string `json:"username"`
	Email    string `json:"email"`
	Password string `json:"password"`
}

RegisterRequest is the JSON request body format at the `/auth/register` endpoint.

func (RegisterRequest) Validate

func (r RegisterRequest) Validate() error

Validate implements Validator on RegisterRequest. Simply check non-empty.

type RegisterResponse

type RegisterResponse struct {
	// `/schema/RegisterResponse.json`
	Schema string `json:"$schema,omitempty"`
	UserId string `json:"user_id"`
}

RegisterResponse is the JSON response format at the `auth/register` endpoint.

type Scount

type Scount struct {
	Schema string `json:"$schema,omitempty"`
	Id     string `json:"id"`
	Title  string `json:"title"`
	Desc   string `json:"description"`
	Owner  string `json:"owner"`
}

Scount describes the scount resource. schema is defined at `Scount.json`.

type ScountQuery

type ScountQuery struct {
	Sid    string
	Uid    string
	Owner  string
	Title  string
	Sort   []db.Sorter
	Paging Paginator
}

ScountQuery describes the url query parameters used for filtering the scounts. schema is defined at `ScountQuery.json`.

func ParseScountQuery

func ParseScountQuery(url.Values) (*ScountQuery, error)

ParseScountQuery parses the query parameters on scount collection resource.

type ScountRequest

type ScountRequest struct {
	Title string `json:"title"`
	Desc  string `json:"description"`
}

ScountRequest describes new scount creation request. schema is defined at `ScountRequest.json`

func (ScountRequest) Validate

func (ScountRequest) Validate() error

Validate implements Validator on ScountRequest.

type ScountResource

type ScountResource struct {
	DB *db.Store
}

ScountResource is the http.Handler for all requests to `/scounts`.

func (ScountResource) CreateScount

func (res ScountResource) CreateScount(w http.ResponseWriter, r *http.Request)

CreateScount handles POST request at `/scounts`.

func (ScountResource) DeleteScount

func (res ScountResource) DeleteScount(w http.ResponseWriter, r *http.Request)

DeleteScount handles DELETE request at `/scounts/{sid}`.

func (ScountResource) GetScount

func (res ScountResource) GetScount(w http.ResponseWriter, r *http.Request)

GetScount handles GET requests at `/scounts/{sid}`.

func (ScountResource) ListScounts

func (res ScountResource) ListScounts(w http.ResponseWriter, r *http.Request)

ListScounts handles GET requests at `/scounts`.

func (ScountResource) Router

func (res ScountResource) Router() chi.Router

Router constructs a new chi.Router for the ScountResource.

func (ScountResource) ServeHTTP

func (res ScountResource) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler on ScountResource.

func (ScountResource) UpdateScount

func (res ScountResource) UpdateScount(w http.ResponseWriter, r *http.Request)

UpdateScount handles PATCH request at `/scounts/{sid}`.

type ScountResponse

type ScountResponse struct {
	Schema   string `json:"$schema,omitempty"`
	ScountId string `json:"scount_id"`
}

ScountResponse points to the newly created scount resource. schema is defined at `ScountResponse.json`

type ScountUpdater

type ScountUpdater struct {
	Title string `json:"title,omitempty"`
	Owner string `json:"owner,omitempty"`
}

ScountUpdater describes scount resource update request. schema is defined at `ScountUpdater.json`

func (ScountUpdater) Validate

func (ScountUpdater) Validate() error

Validate implements Validator on ScountUpdater

type User

type User struct {
	Schema string `json:"$schema,omitempty"`
	Id     string `json:"id"`
	Email  string `json:"email"`
	Name   string `json:"name"`
}

User is the JSON response body for user request fetch request. JSON schema defined in `User.json`.

type UserQuery

type UserQuery struct {
	Id     string
	Email  string
	Name   string
	Sort   []db.Sorter
	Paging Paginator
}

UserQuery defines the query parameters for user collection resource. Schema defined in `UserQuery.json`.

func ParseUserQuery

func ParseUserQuery(query url.Values) (*UserQuery, error)

ParseUserQuery parses the query parameters on user collection resource.

type UserResource

type UserResource struct {
	DB *db.Store
}

UserResource is http.Handler for all requests to `/users`.

func (UserResource) DeleteUser

func (res UserResource) DeleteUser(w http.ResponseWriter, r *http.Request)

DeleteUser handles DELETE method on `users/me` route.

func (UserResource) GetCurrentUser

func (res UserResource) GetCurrentUser(w http.ResponseWriter, r *http.Request)

GetCurrentUser is http.HandlerFunc for `/users/me` GET request.

func (UserResource) GetUser

func (res UserResource) GetUser(w http.ResponseWriter, r *http.Request)

GetUser handles requests at `/users/{uid}`.

func (UserResource) ListUsers

func (res UserResource) ListUsers(w http.ResponseWriter, r *http.Request)

ListUsers handles requests at `/users`.

func (UserResource) Router

func (res UserResource) Router() chi.Router

Router constructs a new chi.Router for the UserResource.

func (UserResource) ServeHTTP

func (res UserResource) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler on UserResource.

func (UserResource) UpdateUser

func (res UserResource) UpdateUser(w http.ResponseWriter, r *http.Request)

UpdateUser is http.HandlerFunc for `/users/me` PATCH request.

type UserUpdater

type UserUpdater struct {
	// /docs/UserUpdater.json
	// Schema string `json:"$schema,omitempty"`
	Username string `json:"username,omitempty"`
}

UserUpdater is JSON request for updating (PATCH) `/me` resource.

func (UserUpdater) Validate

func (UserUpdater) Validate() error

Validate implements Validator on UserUpdater.

type Validator

type Validator interface {
	// Validate checks if `this` is valid.
	// nil error upon success and
	// non-nil error means failure.
	Validate() error
}

Validator is any type that has validation logic defined on it.

type WebLink struct {
	Target     *url.URL
	Attributes map[string]string
}

WebLink defines a link as per RFC8288.

func NewWebLink(path string, query url.Values, rel string) WebLink

NewWebLink constructs a simple web link with target URI obtained from the given path and query, and containing given rel attribute.

func PagingLinks(base string, params url.Values, total int) []WebLink

PagingLinks constructs a list of WebLink from paging parameters parsed from the query params, or fallback to DefaultPaginator in case of error.

func (WebLink) Encode

func (linker WebLink) Encode() string

Encode gives a string representation of the web link as per Link serialization in HTTP headers [[RFC8288:Section-3]].

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL