signup.go 2.33 KB
Newer Older
1 2 3 4
package handlers

import (
	"context"
5 6
	"net/http"

7 8 9
	"geeks-accelerator/oss/saas-starter-kit/internal/account"
	"geeks-accelerator/oss/saas-starter-kit/internal/platform/auth"
	"geeks-accelerator/oss/saas-starter-kit/internal/platform/web"
10 11
	"geeks-accelerator/oss/saas-starter-kit/internal/platform/web/webcontext"
	"geeks-accelerator/oss/saas-starter-kit/internal/platform/web/weberror"
12
	"geeks-accelerator/oss/saas-starter-kit/internal/signup"
13 14
	"github.com/jmoiron/sqlx"
	"github.com/pkg/errors"
15
	"gopkg.in/go-playground/validator.v9"
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
)

// Signup represents the Signup API method handler set.
type Signup struct {
	MasterDB *sqlx.DB

	// ADD OTHER STATE LIKE THE LOGGER AND CONFIG HERE.
}

// Signup godoc
// @Summary Signup handles new account creation.
// @Description Signup creates a new account and user in the system.
// @Tags signup
// @Accept  json
// @Produce  json
// @Param data body signup.SignupRequest true "Signup details"
Lee Brown's avatar
Lee Brown committed
32
// @Success 201 {object} signup.SignupResponse
33 34
// @Failure 400 {object} web.ErrorResponse
// @Failure 500 {object} web.ErrorResponse
35 36
// @Router /signup [post]
func (c *Signup) Signup(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {
Lee Brown's avatar
Lee Brown committed
37 38 39
	v, err := webcontext.ContextValues(ctx)
	if err != nil {
		return err
40 41 42
	}

	// Claims are optional as authentication is not required ATM for this method.
Lee Brown's avatar
Lee Brown committed
43
	claims, _ := auth.ClaimsFromContext(ctx)
44

Lee Brown's avatar
Lee Brown committed
45 46 47 48
	// Hack to allow custom validation to be handled by business logic package.
	ctx = context.WithValue(ctx, signup.KeyTagUniqueEmail, true)
	ctx = context.WithValue(ctx, signup.KeyTagUniqueName, true)

49
	var req signup.SignupRequest
Lee Brown's avatar
Lee Brown committed
50 51 52
	if err := web.Decode(ctx, r, &req); err != nil {
		if _, ok := errors.Cause(err).(*weberror.Error); !ok {
			err = weberror.NewError(ctx, err, http.StatusBadRequest)
53
		}
54
		return web.RespondJsonError(ctx, w, err)
55 56 57 58
	}

	res, err := signup.Signup(ctx, claims, c.MasterDB, req, v.Now)
	if err != nil {
Lee Brown's avatar
Lee Brown committed
59
		switch errors.Cause(err) {
60
		case account.ErrForbidden:
Lee Brown's avatar
Lee Brown committed
61
			return web.RespondJsonError(ctx, w, weberror.NewError(ctx, err, http.StatusForbidden))
62
		default:
63 64
			_, ok := err.(validator.ValidationErrors)
			if ok {
Lee Brown's avatar
Lee Brown committed
65
				return web.RespondJsonError(ctx, w, weberror.NewError(ctx, err, http.StatusBadRequest))
66 67 68
			}

			return errors.Wrapf(err, "Signup: %+v", &req)
69 70 71
		}
	}

Lee Brown's avatar
Lee Brown committed
72
	return web.RespondJson(ctx, w, res.Response(ctx), http.StatusCreated)
73
}