hatecomputers.club/api/profiles/profiles.go

84 lines
2.5 KiB
Go
Raw Normal View History

2024-04-08 19:04:19 -04:00
package profiles
import (
"log"
"net/http"
"git.hatecomputers.club/hatecomputers/hatecomputers.club/adapters/files"
"git.hatecomputers.club/hatecomputers/hatecomputers.club/api/types"
"git.hatecomputers.club/hatecomputers/hatecomputers.club/database"
)
const MaxAvatarSize = 1024 * 1024 * 2 // 2MB
const AvatarPath = "avatars/"
func GetProfileContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
if context.User == nil {
return failure(context, req, resp)
}
(*context.TemplateData)["Profile"] = context.User
return success(context, req, resp)
}
}
func UpdateProfileContinuation(fileAdapter files.FilesAdapter, maxAvatarSize int, avatarPath string) func(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
return func(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
formErrors := types.FormError{
Errors: []string{},
}
err := req.ParseMultipartForm(int64(maxAvatarSize))
if err != nil {
log.Println(err)
formErrors.Errors = append(formErrors.Errors, "avatar file too large")
}
if len(formErrors.Errors) == 0 {
file, _, err := req.FormFile("avatar")
if err != nil {
formErrors.Errors = append(formErrors.Errors, "error uploading avatar")
} else {
defer file.Close()
_, err = fileAdapter.CreateFile(avatarPath+context.User.ID, file)
if err != nil {
log.Println(err)
formErrors.Errors = append(formErrors.Errors, "error saving avatar")
}
}
}
if len(formErrors.Errors) == 0 {
bio := req.FormValue("bio")
location := req.FormValue("location")
website := req.FormValue("website")
context.User.Bio = bio
context.User.Location = location
context.User.Website = website
_, err = database.SaveUser(context.DBConn, context.User)
if err != nil {
formErrors.Errors = append(formErrors.Errors, "error saving profile")
}
}
(*context.TemplateData)["Profile"] = context.User
(*context.TemplateData)["FormError"] = formErrors
if len(formErrors.Errors) > 0 {
log.Println(formErrors.Errors)
resp.WriteHeader(http.StatusBadRequest)
return failure(context, req, resp)
}
return success(context, req, resp)
}
}
}