WASAPhoto/service/api/put-updateusername.go

50 lines
1.4 KiB
Go
Raw Normal View History

2022-11-18 13:05:40 +01:00
package api
import (
"net/http"
"github.com/julienschmidt/httprouter"
2022-11-18 17:18:46 +01:00
"github.com/notherealmarco/WASAPhoto/service/api/authorization"
2022-11-18 18:58:12 +01:00
"github.com/notherealmarco/WASAPhoto/service/api/helpers"
2022-11-18 13:05:40 +01:00
"github.com/notherealmarco/WASAPhoto/service/api/reqcontext"
2022-11-26 15:14:41 +01:00
"github.com/notherealmarco/WASAPhoto/service/database"
2022-11-18 17:18:46 +01:00
"github.com/notherealmarco/WASAPhoto/service/structures"
2022-11-18 13:05:40 +01:00
)
func (rt *_router) UpdateUsername(w http.ResponseWriter, r *http.Request, ps httprouter.Params, ctx reqcontext.RequestContext) {
2022-11-18 17:18:46 +01:00
uid := ps.ByName("user_id")
// check if the user is changing his own username
2022-11-20 19:53:24 +01:00
if !authorization.SendAuthorizationError(ctx.Auth.UserAuthorized, uid, rt.db, w, rt.baseLogger, http.StatusNotFound) {
2022-11-18 17:18:46 +01:00
return
}
// decode request body
2022-11-18 17:18:46 +01:00
var req structures.UserDetails
2022-11-18 18:58:12 +01:00
if !helpers.DecodeJsonOrBadRequest(r.Body, w, &req, rt.baseLogger) {
2022-11-18 17:18:46 +01:00
return
}
// check if the username is valid, and if it's not, send a bad request error
if !helpers.MatchUsernameOrBadRequest(req.Name, w, rt.baseLogger) {
2022-11-29 16:07:42 +01:00
return
}
2022-11-26 15:14:41 +01:00
status, err := rt.db.UpdateUsername(uid, req.Name)
2022-12-22 18:12:00 +01:00
// check if the username already exists
2022-11-26 15:14:41 +01:00
if status == database.ERR_EXISTS {
helpers.SendStatus(http.StatusConflict, w, "Username already exists", rt.baseLogger)
return
}
2022-11-18 17:18:46 +01:00
2022-12-22 18:12:00 +01:00
// handle any other database error
2022-11-18 17:18:46 +01:00
if err != nil {
2022-11-22 23:41:52 +01:00
helpers.SendInternalError(err, "Database error: UpdateUsername", w, rt.baseLogger)
2022-11-18 17:18:46 +01:00
return
}
2022-11-22 23:41:52 +01:00
w.WriteHeader(http.StatusNoContent)
2022-11-18 13:05:40 +01:00
}