Refactoring and comments

This commit is contained in:
Joona Hoikkala
2016-11-23 18:07:38 +02:00
parent ba63bad793
commit 670c20f904
5 changed files with 36 additions and 46 deletions

34
api.go
View File

@ -6,20 +6,8 @@ import (
"github.com/kataras/iris"
)
func GetHandlerMap() map[string]func(*iris.Context) {
return map[string]func(*iris.Context){
"/register": WebRegisterGet,
}
}
func PostHandlerMap() map[string]func(*iris.Context) {
return map[string]func(*iris.Context){
"/register": WebRegisterPost,
"/update": WebUpdatePost,
}
}
func (a AuthMiddleware) Serve(ctx *iris.Context) {
// Serve is an authentication middlware function used to authenticate update requests
func (a authMiddleware) Serve(ctx *iris.Context) {
usernameStr := ctx.RequestHeader("X-Api-User")
password := ctx.RequestHeader("X-Api-Key")
postData := ACMETxt{}
@ -44,7 +32,7 @@ func (a AuthMiddleware) Serve(ctx *iris.Context) {
ctx.JSON(iris.StatusUnauthorized, iris.Map{"error": "unauthorized"})
}
func WebRegisterPost(ctx *iris.Context) {
func webRegisterPost(ctx *iris.Context) {
// Create new user
nu, err := DB.Register()
var regJSON iris.Map
@ -63,25 +51,25 @@ func WebRegisterPost(ctx *iris.Context) {
ctx.JSON(regStatus, regJSON)
}
func WebRegisterGet(ctx *iris.Context) {
func webRegisterGet(ctx *iris.Context) {
// This is placeholder for now
WebRegisterPost(ctx)
webRegisterPost(ctx)
}
func WebUpdatePost(ctx *iris.Context) {
func webUpdatePost(ctx *iris.Context) {
// User auth done in middleware
a := ACMETxt{}
userStr := ctx.RequestHeader("X-API-User")
username, err := getValidUsername(userStr)
if err != nil {
log.Warningf("Error while getting username [%s]. This should never happen because of auth middlware.", userStr)
WebUpdatePostError(ctx, err, iris.StatusUnauthorized)
webUpdatePostError(ctx, err, iris.StatusUnauthorized)
return
}
if err := ctx.ReadJSON(&a); err != nil {
// Handle bad post data
log.Warningf("Could not unmarshal: [%v]", err)
WebUpdatePostError(ctx, err, iris.StatusBadRequest)
webUpdatePostError(ctx, err, iris.StatusBadRequest)
return
}
a.Username = username
@ -90,18 +78,18 @@ func WebUpdatePost(ctx *iris.Context) {
err := DB.Update(a)
if err != nil {
log.Warningf("Error trying to update [%v]", err)
WebUpdatePostError(ctx, errors.New("internal error"), iris.StatusInternalServerError)
webUpdatePostError(ctx, errors.New("internal error"), iris.StatusInternalServerError)
return
}
ctx.JSON(iris.StatusOK, iris.Map{"txt": a.Value})
} else {
log.Warningf("Bad data, subdomain: [%s], txt: [%s]", a.Subdomain, a.Value)
WebUpdatePostError(ctx, errors.New("bad data"), iris.StatusBadRequest)
webUpdatePostError(ctx, errors.New("bad data"), iris.StatusBadRequest)
return
}
}
func WebUpdatePostError(ctx *iris.Context, err error, status int) {
func webUpdatePostError(ctx *iris.Context, err error, status int) {
errStr := fmt.Sprintf("%v", err)
updJSON := iris.Map{"error": errStr}
ctx.JSON(status, updJSON)