github.com/bitcubate/cryptojournal@v1.2.5-0.20171102134152-f578b3d788ab/src/users/actions/update.go (about)

     1  package useractions
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/fragmenta/auth"
     7  	"github.com/fragmenta/auth/can"
     8  	"github.com/fragmenta/mux"
     9  	"github.com/fragmenta/server"
    10  	"github.com/fragmenta/view"
    11  
    12  	"github.com/bitcubate/cryptojournal/src/lib/session"
    13  	"github.com/bitcubate/cryptojournal/src/users"
    14  )
    15  
    16  // HandleUpdateShow renders the form to update a user.
    17  func HandleUpdateShow(w http.ResponseWriter, r *http.Request) error {
    18  
    19  	// Fetch the  params
    20  	params, err := mux.Params(r)
    21  	if err != nil {
    22  		return server.InternalError(err)
    23  	}
    24  
    25  	// Find the user
    26  	user, err := users.Find(params.GetInt(users.KeyName))
    27  	if err != nil {
    28  		return server.NotFoundError(err)
    29  	}
    30  
    31  	// Authorise update user
    32  	err = can.Update(user, session.CurrentUser(w, r))
    33  	if err != nil {
    34  		return server.NotAuthorizedError(err)
    35  	}
    36  
    37  	// Render the template
    38  	view := view.NewRenderer(w, r)
    39  	view.AddKey("user", user)
    40  	return view.Render()
    41  }
    42  
    43  // HandleUpdate handles the POST of the form to update a user
    44  func HandleUpdate(w http.ResponseWriter, r *http.Request) error {
    45  
    46  	// Fetch the  params
    47  	params, err := mux.Params(r)
    48  	if err != nil {
    49  		return server.InternalError(err)
    50  	}
    51  
    52  	// Find the user
    53  	user, err := users.Find(params.GetInt(users.KeyName))
    54  	if err != nil {
    55  		return server.NotFoundError(err)
    56  	}
    57  
    58  	// Check the authenticity token
    59  	err = session.CheckAuthenticity(w, r)
    60  	if err != nil {
    61  		return err
    62  	}
    63  
    64  	// Authorise update user
    65  	err = can.Update(user, session.CurrentUser(w, r))
    66  	if err != nil {
    67  		return server.NotAuthorizedError(err)
    68  	}
    69  
    70  	// Set the password hash from the password
    71  	hash, err := auth.HashPassword(params.Get("password"))
    72  	if err != nil {
    73  		return server.InternalError(err)
    74  	}
    75  	// FIXME: For user update we should require the old password too, to match existing
    76  	params.SetString("password_hash", hash)
    77  
    78  	// Validate the params, removing any we don't accept
    79  	userParams := user.ValidateParams(params.Map(), users.AllowedParams())
    80  
    81  	err = user.Update(userParams)
    82  	if err != nil {
    83  		return server.InternalError(err)
    84  	}
    85  
    86  	// Redirect to user
    87  	return server.Redirect(w, r, user.ShowURL())
    88  }