separate profile model from account model

This commit is contained in:
dhax 2017-10-13 00:11:57 +02:00
parent f729160209
commit c3271d7dcf
15 changed files with 152 additions and 83 deletions

View file

@ -11,7 +11,6 @@ import (
validation "github.com/go-ozzo/ozzo-validation"
"github.com/dhax/go-base/auth"
"github.com/dhax/go-base/models"
)
// AccountStore defines database operations for account.
@ -21,7 +20,6 @@ type AccountStore interface {
Delete(*auth.Account) error
UpdateToken(*auth.Token) error
DeleteToken(*auth.Token) error
UpdateProfile(*models.Profile) error
}
// AccountResource implements account managment handler.
@ -46,7 +44,6 @@ func (rs *AccountResource) router() *chi.Mux {
r.Put("/", rs.updateToken)
r.Delete("/", rs.deleteToken)
})
r.Put("/profile", rs.updateProfile)
return r
}
@ -57,8 +54,7 @@ func (rs *AccountResource) accountCtx(next http.Handler) http.Handler {
account, err := rs.Store.Get(claims.ID)
if err != nil {
// account deleted while access token still valid
log(r).WithField("account", claims.Sub).Warn(err)
render.Render(w, r, ErrNotFound)
render.Render(w, r, ErrUnauthorized)
return
}
ctx := context.WithValue(r.Context(), ctxAccount, account)
@ -68,7 +64,8 @@ func (rs *AccountResource) accountCtx(next http.Handler) http.Handler {
type accountRequest struct {
*auth.Account
// not really neccessary here as we limit updated database columns in store
// override protected data here, although not really neccessary here
// as we limit updated database columns in store as well
ProtectedID int `json:"id"`
ProtectedActive bool `json:"active"`
ProtectedRoles []string `json:"roles"`
@ -174,44 +171,3 @@ func (rs *AccountResource) deleteToken(w http.ResponseWriter, r *http.Request) {
}
render.Respond(w, r, http.NoBody)
}
type profileRequest struct {
*models.Profile
ProtectedID int `json:"id"`
}
func (d *profileRequest) Bind(r *http.Request) error {
// d.ProtectedActive = true
// d.ProtectedRoles = []string{}
return nil
}
type profileResponse struct {
*models.Profile
}
func newProfileResponse(p *models.Profile) *profileResponse {
return &profileResponse{
Profile: p,
}
}
func (rs *AccountResource) updateProfile(w http.ResponseWriter, r *http.Request) {
acc := r.Context().Value(ctxAccount).(*auth.Account)
data := &profileRequest{Profile: acc.Profile}
if err := render.Bind(r, data); err != nil {
render.Render(w, r, ErrInvalidRequest(err))
}
p := data.Profile
if err := rs.Store.UpdateProfile(p); err != nil {
switch err.(type) {
case validation.Errors:
render.Render(w, r, ErrValidation(err))
return
}
render.Render(w, r, ErrRender(err))
return
}
render.Respond(w, r, newProfileResponse(p))
}