hackathon/api/api.go

87 lines
2.1 KiB
Go

2021-09-30 10:32:18 +07:00
//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen@v1.8.2 --package=api --generate types -o types.gen.go ../schema/schema.yaml
//go:generate go run github.com/deepmap/oapi-codegen/cmd/oapi-codegen@v1.8.2 --package=api --generate chi-server -o routes.gen.go ../schema/schema.yaml
package api
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/hhhapz/hackathon/models"
"golang.org/x/oauth2"
)
// inProd tells the server whether it is in prod.
// It should be set using ldflags on build time.
var inProd bool
type Server struct {
*AuthService
*UserService
}
type OAuthStore interface {
Create(callback string) (code string)
Validate(code string) (string, bool)
Exchange(ctx context.Context, code string) (*oauth2.Token, error)
Remove(code string)
}
type UserStore interface {
CreateToken(ctx context.Context, user *models.User) (*models.Token, error)
RevokeToken(ctx context.Context, token string) error
RevokeUserTokens(ctx context.Context, user *models.User) (int64, error)
User(ctx context.Context, email string) (*models.User, error)
Users(ctx context.Context) ([]*models.User, error)
DecodeUser(ctx context.Context, buf []byte) (*models.User, error)
UserByToken(ctx context.Context, token string) (*models.User, error)
UpdateUser(ctx context.Context, user *models.User) error
}
var _ ServerInterface = (*Server)(nil)
func NewServer(oaStore OAuthStore, userStore UserStore) *Server {
return &Server{
AuthService: &AuthService{
oauthStore: oaStore,
userStore: userStore,
},
UserService: &UserService{
userStore: userStore,
},
}
}
func serverError(w http.ResponseWriter, code int, message string) {
w.WriteHeader(code)
json.NewEncoder(w).Encode(Error{
Code: code,
Message: message,
})
}
type parseError struct {
typ string
value string
reason string
message string
}
func newParseError(typ, value, reason string) error {
return parseError{
typ: typ,
value: value,
reason: reason,
message: "invalid %s(%q): %s",
}
}
func (err parseError) Error() string {
return fmt.Sprintf(err.message, err.typ, err.value, err.reason)
}