Semaphore/api/projects/projects.go

67 lines
1.5 KiB
Go
Raw Normal View History

2016-04-02 14:40:07 +02:00
package projects
import (
2017-02-23 00:21:49 +01:00
"net/http"
2017-02-23 06:12:16 +01:00
"github.com/ansible-semaphore/semaphore/db"
"time"
"github.com/ansible-semaphore/semaphore/util"
"github.com/gorilla/context"
"github.com/masterminds/squirrel"
2016-04-02 14:40:07 +02:00
)
// GetProjects returns all projects in this users context
func GetProjects(w http.ResponseWriter, r *http.Request) {
user := context.Get(r, "user").(*db.User)
2016-04-02 14:40:07 +02:00
query, args, err := squirrel.Select("p.*").
From("project as p").
Join("project__user as pu on pu.project_id=p.id").
Where("pu.user_id=?", user.ID).
OrderBy("p.name").
ToSql()
2016-04-02 14:40:07 +02:00
util.LogWarning(err)
var projects []db.Project
2020-11-28 22:49:44 +01:00
if _, err := db.Sql.Select(&projects, query, args...); err != nil {
panic(err)
}
2016-04-02 14:40:07 +02:00
util.WriteJSON(w, http.StatusOK, projects)
2016-04-02 14:40:07 +02:00
}
// AddProject adds a new project to the database
func AddProject(w http.ResponseWriter, r *http.Request) {
var body db.Project
user := context.Get(r, "user").(*db.User)
2016-04-02 14:40:07 +02:00
if err := util.Bind(w, r, &body); err != nil {
return
}
2016-04-02 14:40:07 +02:00
err := body.CreateProject()
if err != nil {
panic(err)
}
2016-04-02 14:40:07 +02:00
2020-11-28 22:49:44 +01:00
if _, err := db.Sql.Exec("insert into project__user (project_id, user_id, `admin`) values (?, ?, 1)", body.ID, user.ID); err != nil {
panic(err)
}
2016-04-02 14:40:07 +02:00
desc := "Project Created"
oType := "Project"
if err := (db.Event{
ProjectID: &body.ID,
Description: &desc,
ObjectType: &oType,
ObjectID: &body.ID,
Created: db.GetParsedTime(time.Now()),
}.Insert()); err != nil {
panic(err)
}
2016-04-17 02:20:23 +02:00
util.WriteJSON(w, http.StatusCreated, body)
2016-04-02 14:40:07 +02:00
}