...
 
Commits (21)
......@@ -51,6 +51,7 @@
},
"Web": {
"BaseURL": "http://localhost:4200/"
"BaseURL": "http://localhost:4200/",
"ImageURL": "http://localhost:9992"
}
}
......@@ -56,7 +56,8 @@ type Data struct {
EmailTemplates Templates
Web struct {
BaseURL string
BaseURL string
ImageURL string
}
}
......
......@@ -14,10 +14,20 @@ type Budget struct {
UserID *int64
ParentID int64
Name string
Description string
Private bool
PrivateBalance bool
}
// LoadBudgetByID loads a budget by UUID from the database
func (context *APIContext) LoadBudgetByID(id int64) (Budget, error) {
budget := Budget{}
err := context.QueryRow("SELECT id, uuid, project_id, user_id, parent, name, description, private, private_balance FROM budgets WHERE id = $1", id).
Scan(&budget.ID, &budget.UUID, &budget.ProjectID, &budget.UserID, &budget.ParentID, &budget.Name, &budget.Description, &budget.Private, &budget.PrivateBalance)
return budget, err
}
// LoadBudgetByUUID loads a budget by UUID from the database
func (context *APIContext) LoadBudgetByUUID(uuid string) (Budget, error) {
budget := Budget{}
......@@ -25,8 +35,8 @@ func (context *APIContext) LoadBudgetByUUID(uuid string) (Budget, error) {
return budget, ErrInvalidID
}
err := context.QueryRow("SELECT id, uuid, project_id, user_id, parent, name, private, private_balance FROM budgets WHERE uuid = $1", uuid).
Scan(&budget.ID, &budget.UUID, &budget.ProjectID, &budget.UserID, &budget.ParentID, &budget.Name, &budget.Private, &budget.PrivateBalance)
err := context.QueryRow("SELECT id, uuid, project_id, user_id, parent, name, description, private, private_balance FROM budgets WHERE uuid = $1", uuid).
Scan(&budget.ID, &budget.UUID, &budget.ProjectID, &budget.UserID, &budget.ParentID, &budget.Name, &budget.Description, &budget.Private, &budget.PrivateBalance)
return budget, err
}
......@@ -37,11 +47,34 @@ func (context *APIContext) LoadRootBudgetForProject(project *Project) (Budget, e
return budget, ErrInvalidID
}
err := context.QueryRow("SELECT id, uuid, project_id, user_id, parent, name, private, private_balance FROM budgets WHERE project_id = $1 AND parent = 0", project.ID).
Scan(&budget.ID, &budget.UUID, &budget.ProjectID, &budget.UserID, &budget.ParentID, &budget.Name, &budget.Private, &budget.PrivateBalance)
err := context.QueryRow("SELECT id, uuid, project_id, user_id, parent, name, description, private, private_balance FROM budgets WHERE project_id = $1 AND parent = 0 ORDER BY id ASC", project.ID).
Scan(&budget.ID, &budget.UUID, &budget.ProjectID, &budget.UserID, &budget.ParentID, &budget.Name, &budget.Description, &budget.Private, &budget.PrivateBalance)
return budget, err
}
// LoadBudgets loads all budgets for a project
func (context *APIContext) LoadBudgets(project *Project) ([]Budget, error) {
budgets := []Budget{}
rows, err := context.Query("SELECT id, uuid, project_id, user_id, parent, name, description, private, private_balance FROM budgets WHERE project_id = $1 AND parent = 0 ORDER BY id ASC", project.ID)
if err != nil {
return budgets, err
}
defer rows.Close()
for rows.Next() {
budget := Budget{}
err = rows.Scan(&budget.ID, &budget.UUID, &budget.ProjectID, &budget.UserID, &budget.ParentID, &budget.Name, &budget.Description, &budget.Private, &budget.PrivateBalance)
if err != nil {
return budgets, err
}
budgets = append(budgets, budget)
}
return budgets, err
}
// GetBudgetByUUID returns a budget by UUID from the cache
func (context *APIContext) GetBudgetByUUID(uuid string) (Budget, error) {
budget := Budget{}
......@@ -58,7 +91,7 @@ func (context *APIContext) GetBudgetByUUID(uuid string) (Budget, error) {
func (context *APIContext) LoadAllBudgets() ([]Budget, error) {
budgets := []Budget{}
rows, err := context.Query("SELECT id, uuid, project_id, user_id, parent, name, private, private_balance FROM budgets")
rows, err := context.Query("SELECT id, uuid, project_id, user_id, parent, name, description, private, private_balance FROM budgets")
if err != nil {
return budgets, err
}
......@@ -66,7 +99,7 @@ func (context *APIContext) LoadAllBudgets() ([]Budget, error) {
defer rows.Close()
for rows.Next() {
budget := Budget{}
err = rows.Scan(&budget.ID, &budget.UUID, &budget.ProjectID, &budget.UserID, &budget.ParentID, &budget.Name, &budget.Private, &budget.PrivateBalance)
err = rows.Scan(&budget.ID, &budget.UUID, &budget.ProjectID, &budget.UserID, &budget.ParentID, &budget.Name, &budget.Description, &budget.Private, &budget.PrivateBalance)
if err != nil {
return budgets, err
}
......@@ -79,12 +112,8 @@ func (context *APIContext) LoadAllBudgets() ([]Budget, error) {
// Update a budget in the database
func (budget *Budget) Update(context *APIContext) error {
_, err := context.Exec("UPDATE budgets SET project_id = $1, user_id = $2, parent = $3, name = $4, private = $5, private_balance = $6 WHERE id = $7",
budget.ProjectID, budget.UserID, budget.ParentID, budget.Name, budget.Private, budget.PrivateBalance, budget.ID)
if err != nil {
panic(err)
}
_, err := context.Exec("UPDATE budgets SET project_id = $1, user_id = $2, parent = $3, name = $4, description = $5, private = $6, private_balance = $7 WHERE id = $8",
budget.ProjectID, budget.UserID, budget.ParentID, budget.Name, budget.Description, budget.Private, budget.PrivateBalance, budget.ID)
budgetsCache.Delete(budget.UUID)
return err
}
......@@ -92,8 +121,16 @@ func (budget *Budget) Update(context *APIContext) error {
// Save a budget to the database
func (budget *Budget) Save(context *APIContext) error {
budget.UUID, _ = UUID()
err := context.QueryRow("INSERT INTO budgets (uuid, project_id, user_id, parent, name, private, private_balance) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id",
budget.UUID, budget.ProjectID, budget.UserID, budget.ParentID, budget.Name, budget.Private, budget.PrivateBalance).Scan(&budget.ID)
err := context.QueryRow("INSERT INTO budgets (uuid, project_id, user_id, parent, name, description, private, private_balance) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id",
budget.UUID, budget.ProjectID, budget.UserID, budget.ParentID, budget.Name, budget.Description, budget.Private, budget.PrivateBalance).Scan(&budget.ID)
budgetsCache.Delete(budget.UUID)
return err
}
// Delete a budget from the database
func (budget *Budget) Delete(context *APIContext) error {
_, err := context.Exec("DELETE FROM budgets WHERE id = $1", budget.ID)
budgetsCache.Delete(budget.UUID)
return err
}
......@@ -101,7 +138,7 @@ func (budget *Budget) Save(context *APIContext) error {
// Balance returns this budget's total balance
func (budget *Budget) Balance(context *APIContext) (int64, error) {
var val int64
err := context.QueryRow("SELECT SUM(amount) FROM transactions WHERE budget_id = $1", budget.ID).
err := context.QueryRow("SELECT COALESCE(SUM(amount), 0) FROM transactions WHERE budget_id = $1", budget.ID).
Scan(&val)
return val, err
}
......
......@@ -45,6 +45,11 @@ func (context *APIContext) LoadCodeByID(id int64) (Code, error) {
return code, err
}
// LoadCodeByBudgetID loads a code by a single budgetID from the database
func (context *APIContext) LoadCodeByBudgetUUID(budgetID string) (Code, error) {
return context.LoadCodeByBudgetsAndRatios([]string{budgetID}, []string{"100"}, "")
}
// LoadCodeByBudgetsAndRatios loads a code by budgetIDs and their ratios from the database
func (context *APIContext) LoadCodeByBudgetsAndRatios(budgetIDs, ratios StringSlice, userID string) (Code, error) {
code := Code{}
......@@ -76,7 +81,10 @@ func (context *APIContext) LoadCodeByBudgetsAndRatios(budgetIDs, ratios StringSl
}
// user may be empty
user, _ := context.GetUserByUUID(userID)
var user User
if userID != "" {
user, _ = context.GetUserByUUID(userID)
}
// sort budgets & ratios
sort.Sort(BudgetSorter(BudgetRatioPair{bids, ratios}))
......
......@@ -39,7 +39,15 @@ func SetupPostgres(pc config.PostgreSQLConnection) {
// connection on further calls
func GetDatabase() *sql.DB {
if pgDB == nil {
var err error
c := pgConfig
c.DbName = ""
db, err := sql.Open("postgres", c.Marshal())
if err != nil {
panic(err)
}
db.Query("CREATE DATABASE " + pgConfig.DbName)
pgDB, err = sql.Open("postgres", pgConfig.Marshal())
if err != nil {
panic(err)
......@@ -90,6 +98,7 @@ func InitDatabase() {
created_at timestamp NOT NULL,
private bool DEFAULT false,
private_balance bool DEFAULT true,
processing_cut int DEFAULT 10,
activated bool DEFAULT false,
CONSTRAINT uk_projects_uuid UNIQUE (uuid),
CONSTRAINT uk_projects_slug UNIQUE (slug),
......
......@@ -3,6 +3,7 @@ package db
import (
"crypto/sha1"
"encoding/hex"
"errors"
"io/ioutil"
"net/url"
"path"
......@@ -16,6 +17,10 @@ func (context *APIContext) LoadImage(id string) ([]byte, error) {
// StoreImage writes an image to disk and returns the hashsum
func (context *APIContext) StoreImage(logo []byte) (string, error) {
if len(logo) == 0 {
return "", errors.New("empty image data")
}
sha := sha1.New()
sha.Write([]byte(logo))
shasum := hex.EncodeToString(sha.Sum(nil))
......@@ -29,10 +34,10 @@ func (context *APIContext) StoreImage(logo []byte) (string, error) {
// BuildImageURL returns the canonical URL for an image
func (context *APIContext) BuildImageURL(id string, placeholder string) string {
u, _ := url.Parse(context.Config.Web.BaseURL)
u, _ := url.Parse(context.Config.Web.ImageURL)
if id == "" {
u.Path = path.Join(u.Path, "images", placeholder+".png")
u.Path = path.Join(u.Path, placeholder+".png")
} else {
u.Path = path.Join(u.Path, "images", id)
}
......
......@@ -19,6 +19,7 @@ type Project struct {
CreatedAt time.Time
Private bool
PrivateBalance bool
ProcessingCut int64
Activated bool
}
......@@ -29,8 +30,8 @@ func (context *APIContext) LoadProjectByUUID(uuid string) (Project, error) {
return project, ErrInvalidID
}
err := context.QueryRow("SELECT id, uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance, activated FROM projects WHERE uuid = $1", uuid).
Scan(&project.ID, &project.UUID, &project.Slug, &project.Name, &project.Summary, &project.About, &project.Website, &project.License, &project.Repository, &project.Logo, &project.CreatedAt, &project.Private, &project.PrivateBalance, &project.Activated)
err := context.QueryRow("SELECT id, uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance, processing_cut, activated FROM projects WHERE uuid = $1", uuid).
Scan(&project.ID, &project.UUID, &project.Slug, &project.Name, &project.Summary, &project.About, &project.Website, &project.License, &project.Repository, &project.Logo, &project.CreatedAt, &project.Private, &project.PrivateBalance, &project.ProcessingCut, &project.Activated)
return project, err
}
......@@ -41,8 +42,8 @@ func (context *APIContext) GetProjectByID(id int64) (Project, error) {
return project, ErrInvalidID
}
err := context.QueryRow("SELECT id, uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance, activated FROM projects WHERE id = $1", id).
Scan(&project.ID, &project.UUID, &project.Slug, &project.Name, &project.Summary, &project.About, &project.Website, &project.License, &project.Repository, &project.Logo, &project.CreatedAt, &project.Private, &project.PrivateBalance, &project.Activated)
err := context.QueryRow("SELECT id, uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance, processing_cut, activated FROM projects WHERE id = $1", id).
Scan(&project.ID, &project.UUID, &project.Slug, &project.Name, &project.Summary, &project.About, &project.Website, &project.License, &project.Repository, &project.Logo, &project.CreatedAt, &project.Private, &project.PrivateBalance, &project.ProcessingCut, &project.Activated)
return project, err
}
......@@ -65,8 +66,8 @@ func (context *APIContext) LoadProjectBySlug(slug string) (Project, error) {
return project, ErrInvalidID
}
err := context.QueryRow("SELECT id, uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance, activated FROM projects WHERE slug = $1", slug).
Scan(&project.ID, &project.UUID, &project.Slug, &project.Name, &project.Summary, &project.About, &project.Website, &project.License, &project.Repository, &project.Logo, &project.CreatedAt, &project.Private, &project.PrivateBalance, &project.Activated)
err := context.QueryRow("SELECT id, uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance, processing_cut, activated FROM projects WHERE slug = $1", slug).
Scan(&project.ID, &project.UUID, &project.Slug, &project.Name, &project.Summary, &project.About, &project.Website, &project.License, &project.Repository, &project.Logo, &project.CreatedAt, &project.Private, &project.PrivateBalance, &project.ProcessingCut, &project.Activated)
return project, err
}
......@@ -74,7 +75,7 @@ func (context *APIContext) LoadProjectBySlug(slug string) (Project, error) {
func (context *APIContext) LoadAllProjects() ([]Project, error) {
projects := []Project{}
rows, err := context.Query("SELECT id, uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance, activated FROM projects")
rows, err := context.Query("SELECT id, uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance, processing_cut, activated FROM projects")
if err != nil {
return projects, err
}
......@@ -82,7 +83,7 @@ func (context *APIContext) LoadAllProjects() ([]Project, error) {
defer rows.Close()
for rows.Next() {
project := Project{}
err = rows.Scan(&project.ID, &project.UUID, &project.Slug, &project.Name, &project.Summary, &project.About, &project.Website, &project.License, &project.Repository, &project.Logo, &project.CreatedAt, &project.Private, &project.PrivateBalance, &project.Activated)
err = rows.Scan(&project.ID, &project.UUID, &project.Slug, &project.Name, &project.Summary, &project.About, &project.Website, &project.License, &project.Repository, &project.Logo, &project.CreatedAt, &project.Private, &project.PrivateBalance, &project.ProcessingCut, &project.Activated)
if err != nil {
return projects, err
}
......@@ -95,11 +96,8 @@ func (context *APIContext) LoadAllProjects() ([]Project, error) {
// Update a project in the database
func (project *Project) Update(context *APIContext) error {
_, err := context.Exec("UPDATE projects SET about = $1, summary = $2, slug = $3, name = $4, website = $5, license = $6, repository = $7, private = $8, private_balance = $9 WHERE id = $10",
project.About, project.Summary, project.Slug, project.Name, project.Website, project.License, project.Repository, project.Private, project.PrivateBalance, project.ID)
if err != nil {
panic(err)
}
_, err := context.Exec("UPDATE projects SET about = $1, summary = $2, slug = $3, name = $4, website = $5, license = $6, repository = $7, private = $8, private_balance = $9, processing_cut = $10 WHERE id = $11",
project.About, project.Summary, project.Slug, project.Name, project.Website, project.License, project.Repository, project.Private, project.PrivateBalance, project.ProcessingCut, project.ID)
projectsCache.Delete(project.UUID)
return err
......@@ -109,8 +107,8 @@ func (project *Project) Update(context *APIContext) error {
func (project *Project) Save(context *APIContext) error {
project.UUID, _ = UUID()
err := context.QueryRow("INSERT INTO projects (uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING id",
project.UUID, project.Slug, project.Name, project.Summary, project.About, project.Website, project.License, project.Repository, project.Logo, project.CreatedAt, project.Private, project.PrivateBalance).Scan(&project.ID)
err := context.QueryRow("INSERT INTO projects (uuid, slug, name, summary, about, website, license, repository, logo, created_at, private, private_balance, processing_cut) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING id",
project.UUID, project.Slug, project.Name, project.Summary, project.About, project.Website, project.License, project.Repository, project.Logo, time.Now().UTC(), project.Private, project.PrivateBalance, project.ProcessingCut).Scan(&project.ID)
projectsCache.Delete(project.UUID)
return err
}
......
......@@ -3,6 +3,7 @@ package main
import (
"os"
"gitlab.techcultivation.org/sangha/mq"
"gitlab.techcultivation.org/sangha/sangha/config"
"gitlab.techcultivation.org/sangha/sangha/db"
"gitlab.techcultivation.org/sangha/sangha/logger"
......@@ -42,6 +43,7 @@ func main() {
log.Infoln("Starting sangha JSON API")
db.SetupPostgres(config.Settings.Connections.PostgreSQL)
mq.SetupAMQP(config.Settings.Connections.AMQP)
if err := RootCmd.Execute(); err != nil {
os.Exit(-1)
......
......@@ -14,10 +14,11 @@ type BudgetResource struct {
}
var (
_ smolder.GetIDSupported = &BudgetResource{}
_ smolder.GetSupported = &BudgetResource{}
_ smolder.PostSupported = &BudgetResource{}
_ smolder.PutSupported = &BudgetResource{}
_ smolder.GetIDSupported = &BudgetResource{}
_ smolder.GetSupported = &BudgetResource{}
_ smolder.PostSupported = &BudgetResource{}
_ smolder.PutSupported = &BudgetResource{}
_ smolder.DeleteSupported = &BudgetResource{}
)
// Register this resource with the container to setup all the routes
......
package budgets
import (
"net/http"
"gitlab.techcultivation.org/sangha/sangha/db"
"github.com/emicklei/go-restful"
"github.com/muesli/smolder"
)
// DeleteAuthRequired returns true because all requests need authentication
func (r *BudgetResource) DeleteAuthRequired() bool {
return true
}
// DeleteDoc returns the description of this API endpoint
func (r *BudgetResource) DeleteDoc() string {
return "delete a budget"
}
// DeleteParams returns the parameters supported by this API endpoint
func (r *BudgetResource) DeleteParams() []*restful.Parameter {
return nil
}
// Post processes an incoming POST (create) request
func (r *BudgetResource) Delete(context smolder.APIContext, request *restful.Request, response *restful.Response) {
auth, err := context.Authentication(request)
if err != nil || auth.(db.Budget).ID != 1 {
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
http.StatusUnauthorized,
false,
"Admin permission required for this operation",
"BudgetResource DELETE"))
return
}
ctx := context.(*db.APIContext)
budget, err := ctx.GetBudgetByUUID(request.PathParameter("budget-id"))
if err != nil {
r.NotFound(request, response)
return
}
err = budget.Delete(ctx)
if err != nil {
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
http.StatusInternalServerError,
true,
"Can't delete budget",
"BudgetResource DELETE"))
return
}
resp := BudgetResponse{}
resp.Init(context)
resp.Send(response)
}
......@@ -26,6 +26,7 @@ func (r *BudgetResource) GetDoc() string {
func (r *BudgetResource) GetParams() []*restful.Parameter {
params := []*restful.Parameter{}
params = append(params, restful.QueryParameter("name", "name of a budget").DataType("string"))
params = append(params, restful.QueryParameter("project", "slug of a project").DataType("string"))
return params
}
......@@ -50,17 +51,31 @@ func (r *BudgetResource) GetByIDs(context smolder.APIContext, request *restful.R
// Get sends out items matching the query parameters
func (r *BudgetResource) Get(context smolder.APIContext, request *restful.Request, response *restful.Response, params map[string][]string) {
ctx := context.(*db.APIContext)
resp := BudgetResponse{}
resp.Init(context)
budgets, err := context.(*db.APIContext).LoadAllBudgets()
if err != nil {
r.NotFound(request, response)
return
}
if len(params["project"]) > 0 {
project, err := ctx.GetProjectByUUID(params["project"][0])
if err != nil {
r.NotFound(request, response)
return
}
for _, budget := range budgets {
resp.AddBudget(&budget)
budgets, _ := ctx.LoadBudgets(&project)
for _, budget := range budgets {
resp.AddBudget(&budget)
}
} else {
budgets, err := ctx.LoadAllBudgets()
if err != nil {
r.NotFound(request, response)
return
}
for _, budget := range budgets {
resp.AddBudget(&budget)
}
}
resp.Send(response)
......
......@@ -12,9 +12,10 @@ import (
// BudgetPostStruct holds all values of an incoming POST request
type BudgetPostStruct struct {
Budget struct {
ProjectID int64 `json:"project_id"`
Project string `json:"project"`
ParentID int64 `json:"parent_id"`
Name string `json:"name"`
Description string `json:"description"`
Private bool `json:"private"`
PrivateBalance bool `json:"private_balance"`
} `json:"budget"`
......@@ -49,15 +50,28 @@ func (r *BudgetResource) Post(context smolder.APIContext, data interface{}, requ
ups := data.(*BudgetPostStruct)
project, err := context.(*db.APIContext).LoadProjectByUUID(ups.Budget.Project)
if err != nil {
panic(err)
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
http.StatusInternalServerError,
true,
"No such project",
"BudgetResource POST"))
return
}
budget := db.Budget{
ProjectID: &ups.Budget.ProjectID,
ProjectID: &project.ID,
ParentID: ups.Budget.ParentID,
Name: ups.Budget.Name,
Description: ups.Budget.Description,
Private: ups.Budget.Private,
PrivateBalance: ups.Budget.PrivateBalance,
}
err := budget.Save(context.(*db.APIContext))
err = budget.Save(context.(*db.APIContext))
if err != nil {
panic(err)
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
http.StatusInternalServerError,
true,
......
......@@ -51,7 +51,18 @@ func (r *BudgetResource) Put(context smolder.APIContext, data interface{}, reque
} */
pps := data.(*BudgetPutStruct)
budget.ProjectID = &pps.Budget.ProjectID
project, err := context.(*db.APIContext).LoadProjectByUUID(pps.Budget.Project)
if err != nil {
panic(err)
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
http.StatusInternalServerError,
true,
"No such project",
"BudgetResource POST"))
return
}
budget.ProjectID = &project.ID
budget.Name = pps.Budget.Name
budget.Private = pps.Budget.Private
budget.PrivateBalance = pps.Budget.PrivateBalance
......
package codes
import (
"fmt"
"strconv"
"gitlab.techcultivation.org/sangha/sangha/db"
"github.com/emicklei/go-restful"
......@@ -42,12 +39,7 @@ func (r *CodeResource) GetByIDs(context smolder.APIContext, request *restful.Req
resp.Init(context)
for _, id := range ids {
iid, err := strconv.Atoi(id)
if err != nil {
r.NotFound(request, response)
return
}
code, err := context.(*db.APIContext).GetCodeByID(int64(iid))
code, err := context.(*db.APIContext).LoadCodeByCode(id)
if err != nil {
r.NotFound(request, response)
return
......
......@@ -54,8 +54,9 @@ func (r *ProjectResource) Post(context smolder.APIContext, data interface{}, req
return
}*/
ctx := context.(*db.APIContext)
ups := data.(*ProjectPostStruct)
_, err := context.(*db.APIContext).LoadProjectBySlug(ups.Project.Slug)
_, err := ctx.LoadProjectBySlug(ups.Project.Slug)
if err == nil {
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
http.StatusBadRequest,
......@@ -77,18 +78,21 @@ func (r *ProjectResource) Post(context smolder.APIContext, data interface{}, req
PrivateBalance: true,
}
logo, err := base64.StdEncoding.DecodeString(ups.Project.Logo)
if err == nil {
project.Logo, err = context.(*db.APIContext).StoreImage(logo)
if err != nil {
log.Println("WARNING: could not store image:", err)
if len(ups.Project.Logo) > 0 {
logo, err := base64.StdEncoding.DecodeString(ups.Project.Logo)
if err == nil {
project.Logo, err = ctx.StoreImage(logo)
if err != nil {
log.Println("WARNING: could not store image:", err)
}
} else {
log.Println("WARNING: could not decode logo:", err)
}
} else {
log.Println("WARNING: could not decode logo:", err)
}
err = project.Save(context.(*db.APIContext))
err = project.Save(ctx)
if err != nil {
panic(err)
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
http.StatusInternalServerError,
true,
......@@ -104,7 +108,7 @@ func (r *ProjectResource) Post(context smolder.APIContext, data interface{}, req
Private: false,
PrivateBalance: true,
}
err = budget.Save(context.(*db.APIContext))
err = budget.Save(ctx)
if err != nil {
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
http.StatusInternalServerError,
......
......@@ -3,7 +3,7 @@ package sessions
import (
"net/http"
"gitlab.techcultivation.org/techcultivation/sangha/db"
"gitlab.techcultivation.org/sangha/sangha/db"
"github.com/emicklei/go-restful"
"github.com/muesli/smolder"
......@@ -23,7 +23,7 @@ type SessionResponse struct {
smolder.Response
IDToken string `json:"id_token"`
UserID int64 `json:"user_id"`
UserID string `json:"user_id"`
}
// SessionPostStruct holds all values of an incoming POST request
......@@ -83,20 +83,11 @@ func (r *SessionResource) PostParams() []*restful.Parameter {
}
// Post processes an incoming POST (create) request
func (r *SessionResource) Post(context smolder.APIContext, request *restful.Request, response *restful.Response) {
func (r *SessionResource) Post(context smolder.APIContext, data interface{}, request *restful.Request, response *restful.Response) {
resp := SessionResponse{}
resp.Init(context)
sps := SessionPostStruct{}
err := request.ReadEntity(&sps)
if err != nil {
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
http.StatusBadRequest,
false,
"Can't parse POST data",
"SessionResource PUT"))
return
}
sps := data.(*SessionPostStruct)
user := db.User{}
if len(sps.Token) > 0 {
......@@ -111,6 +102,7 @@ func (r *SessionResource) Post(context smolder.APIContext, request *restful.Requ
user.UpdatePassword(context.(*db.APIContext), sps.Password)
}
} else {
var err error
user, err = context.(*db.APIContext).GetUserByNameAndPassword(sps.Username, sps.Password)
if err != nil {
smolder.ErrorResponseHandler(request, response, smolder.NewErrorResponse(
......@@ -144,6 +136,20 @@ func (r *SessionResource) Post(context smolder.APIContext, request *restful.Requ
}
resp.IDToken = user.AuthToken[len(user.AuthToken)-1]
resp.UserID = user.ID
resp.UserID = user.UUID
response.WriteHeaderAndEntity(http.StatusOK, resp)
}
// Reads returns the model that will be read by POST, PUT & PATCH operations
func (r *SessionResource) Reads() interface{} {
return &SessionPostStruct{}
}
// Returns returns the model that will be returned
func (r *SessionResource) Returns() interface{} {
return SessionResponse{}
}
func (r *SessionResource) Validate(context smolder.APIContext, data interface{}, request *restful.Request) error {
return nil
}
......@@ -23,6 +23,7 @@ type userInfoResponse struct {
ZIP string `json:"zip"`
City string `json:"city"`
Country string `json:"country"`
Admin bool `json:"admin"`
Activated bool `json:"activated"`
}
......@@ -62,6 +63,7 @@ func prepareUserResponse(context smolder.APIContext, user *db.User) userInfoResp
ZIP: user.ZIP,
City: user.City,
Country: user.Country,
Admin: user.ID == 1,
Activated: user.Activated,
}
......