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/" const AvatarPrefix = "/uploads/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, avatarPrefix 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 file == nil { formErrors.Errors = append(formErrors.Errors, "avatar required") } 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") } } } bio := req.FormValue("bio") location := req.FormValue("location") website := req.FormValue("website") if len(bio) > 128 { formErrors.Errors = append(formErrors.Errors, "bio too long, keep it to 128") } if len(location) > 32 { formErrors.Errors = append(formErrors.Errors, "location too long, keep it to 32") } if len(website) > 64 { formErrors.Errors = append(formErrors.Errors, "website too long, keep it to 64") } if len(formErrors.Errors) == 0 { context.User.Bio = bio context.User.Location = location context.User.Website = website context.User.Avatar = avatarPrefix + context.User.ID _, 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) } } }