func serveGetEnvelopes(w http.ResponseWriter, r *http.Request) chatable.CompoundError { withUsername := mux.Vars(r)["username"] params := r.URL.Query() pg := params.Get("page") page, err := strconv.Atoi(pg) if err != nil || page < 1 { page = 1 } offset := page - 1 activeUser := auth.ActiveUser(r) // this should never happen if activeUser == nil { return auth.ErrUnauthenticated } withUser, err := store.UserStore.GetByUsername(withUsername) if err == sql.ErrNoRows { return chatable.NewUserError("unknown username") } else if err != nil { return chatable.NewServerError(err.Error()) } envelopes, err := store.EnvelopeStore.GetByUserIDWithUserID( activeUser.ID, withUser.ID, offset) if err != nil { return chatable.NewServerError(err.Error()) } var pubEnv []*chatable.PublicEnvelope for _, env := range envelopes { pubEnv = append(pubEnv, env.ToPublic(store.UserStore)) } return writeJSON(w, chatable.NewJSONResult(pubEnv, page)) }
func serveCreateUser(w http.ResponseWriter, r *http.Request) chatable.CompoundError { if err := r.ParseForm(); err != nil { return chatable.NewServerError(err.Error()) } valid := usersForm.Valid(r.PostForm) if !valid { return usersForm.ConsolidateErrors() } u := chatable.NewUser(usersForm.Values["first_name"].(string), usersForm.Values["last_name"].(string), usersForm.Values["username"].(string), usersForm.Values["password"].(string), usersForm.Values["email"].(string), usersForm.Values["phone"].(string), r.RemoteAddr) err := store.UserStore.Create(u) // TODO: refine the error message if err != nil { msg := err.Error() if strings.Contains(msg, "violates") { return chatable.NewUserError("Some fileds are not unique") } return chatable.NewServerError(msg) } // create a auth token token, err := createNewAuthToken(w, r, u) if err != nil { return chatable.NewServerError(err.Error()) } data := []chatable.UserWithToken{ chatable.UserWithToken{ FirstName: u.FirstName, LastName: u.LastName, Username: u.Username, Email: u.Email, PhoneNumber: u.PhoneNumber, Token: *token, }, } return writeJSON(w, chatable.NewJSONResult(data, 1)) }