harness-drone/handler/api/users/create.go
2019-02-19 15:56:41 -08:00

83 lines
2 KiB
Go

// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
package users
import (
"encoding/json"
"net/http"
"time"
"github.com/dchest/uniuri"
"github.com/drone/drone/core"
"github.com/drone/drone/handler/api/render"
"github.com/drone/drone/logger"
)
type userWithToken struct {
*core.User
Token string `json:"token"`
}
// HandleCreate returns an http.HandlerFunc that processes an http.Request
// to create the named user account in the system.
func HandleCreate(users core.UserStore, sender core.WebhookSender) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
in := new(core.User)
err := json.NewDecoder(r.Body).Decode(in)
if err != nil {
render.BadRequest(w, err)
logger.FromRequest(r).WithError(err).
Debugln("api: cannot unmarshal request body")
return
}
user := &core.User{
Login: in.Login,
Active: true,
Admin: in.Admin,
Machine: in.Machine,
Created: time.Now().Unix(),
Updated: time.Now().Unix(),
Hash: in.Hash,
}
if user.Hash == "" {
user.Hash = uniuri.NewLen(32)
}
//
// TODO(bradrydzewski) validate the user.Login with a user.Validate() function
//
err = users.Create(r.Context(), user)
if err == core.ErrUserLimit {
render.ErrorCode(w, err, 402)
logger.FromRequest(r).WithError(err).
Errorln("api: cannot create user")
return
}
if err != nil {
render.InternalError(w, err)
logger.FromRequest(r).WithError(err).
Warnln("api: cannot create user")
return
}
err = sender.Send(r.Context(), &core.WebhookData{
Event: core.WebhookEventUser,
Action: core.WebhookActionCreated,
User: user,
})
if err != nil {
logger.FromRequest(r).WithError(err).
Warnln("api: cannot send webhook")
}
var out interface{} = user
// if the user is a machine account the api token
// is included in the response.
if user.Machine {
out = &userWithToken{user, user.Hash}
}
render.JSON(w, out, 200)
}
}