// DeleteFormdata calls the Delete method from Contacts via RPC (Formdata client). Returns results via jsonapi. func DeleteAllFormdata(w http.ResponseWriter, r *http.Request) { logs.Debug("DeleteAllFormdata") form_id, err := strconv.Atoi(router.Context(r).Param("form_id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"form_id": "not integer"}, http.StatusBadRequest) return } contact_id, err := strconv.Atoi(router.Context(r).Param("contact_id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"contact_id": "not integer"}, http.StatusBadRequest) return } var ( contactClient = rpcClient(r, "ContactClient") args = models.FormdataArgs{Formdata: &models.Formdata{GroupID: router.Context(r).Env["GroupID"].(uint)}} reply = models.FormdataReply{} ) //args.Formdata.ID = uint(id) args.Formdata.FormID = uint(form_id) args.Formdata.ContactID = uint(contact_id) err = contactClient.Call("Formdata.DeleteAll", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, nil, http.StatusNoContent) }
// CreateTag calls the Create method from Contacts via RPC (Tag client). Returns results via jsonapi. func CreateTag(w http.ResponseWriter, r *http.Request) { var ( args = models.TagArgs{GroupID: router.Context(r).Env["GroupID"].(uint)} ) args.Tag = new(models.Tag) CID, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } args.ContactID = uint(CID) if err := Request(&views.Tag{Tag: args.Tag}, r); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"tag": err.Error()}, http.StatusBadRequest) return } var ( contactClient = rpcClient(r, "ContactClient") reply = models.TagReply{} ) err = contactClient.Call("Tag.Create", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Tag{Tag: reply.Tag}, http.StatusOK) }
// RetrieveRefvaluecollection calls the RetrieveCollection method from Forms via RPC (Refvalue client). Returns results via jsonapi. func RetrieveRefvalueCollection(w http.ResponseWriter, r *http.Request) { var ( formClient = rpcClient(r, "FormClient") args = models.RefvalueArgs{Refvalue: &models.Refvalue{GroupID: router.Context(r).Env["GroupID"].(uint)}} reply = models.RefvalueReply{} ) CID, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } args.FormID = uint(CID) err = formClient.Call("Refvalue.RetrieveCollection", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } if reply.Refvalues == nil { reply.Refvalues = make([]models.Refvalue, 0) } Success(w, r, views.Refvalues{Refvalues: reply.Refvalues}, http.StatusOK) }
// DeleteForm calls the Delete method from Forms via RPC (Form client). Returns results via jsonapi. func DeleteForm(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } var ( formClient = rpcClient(r, "FormClient") args = models.FormArgs{Form: &models.Form{GroupID: router.Context(r).Env["GroupID"].(uint)}} reply = models.FormReply{} ) args.Form.ID = uint(id) err = formClient.Call("Form.Delete", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } rep := models.FormReply{} err = formClient.Call("Search.UnIndex", args, &rep) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, nil, http.StatusNoContent) }
// DeleteTag calls the Delete method from Contacts via RPC (Tag client). Returns results via jsonapi. func DeleteTag(w http.ResponseWriter, r *http.Request) { TID, err := strconv.Atoi(router.Context(r).Param("tag_id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"tag_id": "not integer"}, http.StatusBadRequest) return } id, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } var ( contactClient = rpcClient(r, "ContactClient") args = models.TagArgs{GroupID: router.Context(r).Env["GroupID"].(uint)} reply = models.TagReply{} ) args.Tag = new(models.Tag) args.Tag.ID = uint(TID) args.ContactID = uint(id) err = contactClient.Call("Tag.Delete", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, nil, http.StatusNoContent) }
// CreateFormdata calls the Create method from Contacts via RPC (Formdata client). Returns results via jsonapi. func CreateFormdata(w http.ResponseWriter, r *http.Request) { var ( args = models.FormdataArgs{Formdata: &models.Formdata{GroupID: router.Context(r).Env["GroupID"].(uint)}} ) CID, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } args.Formdata.ContactID = uint(CID) if err := Request(&views.Formdata{Formdata: args.Formdata}, r); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"formdata": err.Error()}, http.StatusBadRequest) return } date := time.Now() args.Formdata.Date = &date var ( contactClient = rpcClient(r, "ContactClient") reply = models.FormdataReply{} ) err = contactClient.Call("Formdata.Create", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Formdata{Formdata: reply.Formdata}, http.StatusOK) }
// Middleware that takes care of the authentication. If the token is not correct or there is no token, an error is returned func Authenticate(h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { // Pour desactiver l'authentification // router.Context(r).Env["GroupID"] = uint(1) // router.Context(r).Env["UserID"] = uint(1) // h.ServeHTTP(w, r) // return // token := strings.TrimLeft(r.Header.Get("Authorization"), "Bearer ") if token == "" { logs.Debug("No token found") Fail(w, r, "missing bearer authorization token", http.StatusBadRequest) } else { body, _ := Bearer(r, "OAuth2", "/oauth2/info", token) resp := make(map[string]interface{}) if err := json.Unmarshal(body, &resp); err != nil { logs.Error(err) Fail(w, r, map[string]string{"Authentication": err.Error()}, http.StatusBadRequest) return } if resp["error"] != nil { // refresh := strings.TrimLeft(r.Header.Get("Refresh"), "Refresh ") // r.Form = make(url.Values) // r.Form.Add("grant_type", "refresh_token") // r.Form.Add("refresh_token", refresh) // logs.Debug(refresh) // body, _ := ServiceBody(PostMethod, r, "OAuth2", "/oauth2/token", "application/x-www-form-urlencoded", []byte(r.Form.Encode())) // resp := make(map[string]interface{}) // if err := json.Unmarshal(body, &resp); err != nil { // logs.Error(err) // Fail(w, r, map[string]string{"Authentication": err.Error()}, http.StatusBadRequest) // return // } // logs.Debug(resp) // if resp["error"] != nil { logs.Debug("Token expired") Fail(w, r, "Token", http.StatusBadRequest) // } } else { s := strings.Split(resp["owner"].(string), ":") ID, _ := strconv.Atoi(s[0]) groupID, _ := strconv.Atoi(s[1]) router.Context(r).Env["GroupID"] = uint(groupID) router.Context(r).Env["UserID"] = uint(ID) if ID == 0 { logs.Error(errors.New("ID is 0, no such user")) Fail(w, r, map[string]string{"ID": "is 0"}, http.StatusBadRequest) return } logs.Debug("Authentication done") h.ServeHTTP(w, r) } } } return http.HandlerFunc(fn) }
// Middleware that convert the goji Context to a context usable by Mux func (app Gojimux) putContext(handle http.HandlerFunc) func(web.C, http.ResponseWriter, *http.Request) { fn := func(c web.C, w http.ResponseWriter, r *http.Request) { param := new(router.Param) for name, value := range c.URLParams { param.Name = name param.Value = value router.Context(r).Params = append(router.Context(r).Params, *param) } handle(w, r) } return fn }
// UpdateContact calls the Update method from Contacts via RPC (Contact client). Returns results via jsonapi. func UpdateContact(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } var ( args = models.ContactArgs{Contact: &models.Contact{GroupID: router.Context(r).Env["GroupID"].(uint)}} ) if err := Request(&views.Contact{Contact: args.Contact}, r); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"contact": err.Error()}, http.StatusBadRequest) return } var coordonnees [2]string = Geoloc(&args) if coordonnees[0] == "noresponse" { err := errors.New("noresponse") Error(w, r, err.Error(), http.StatusBadRequest) return } args.Contact.Address.Latitude = coordonnees[0] args.Contact.Address.Longitude = coordonnees[1] var ( contactClient = rpcClient(r, "ContactClient") reply = models.ContactReply{} ) args.Contact.ID = uint(id) err = contactClient.Call("Contact.Update", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } rep := models.ContactReply{} args.Contact = reply.Contact err = contactClient.Call("Search.Index", args, &rep) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Contact{Contact: reply.Contact}, http.StatusOK) }
// CreateFact calls the Create method from Contacts via RPC (Fact client). Returns results via jsonapi. func CreateFact(w http.ResponseWriter, r *http.Request) { var args = models.FactArgs{Fact: &models.Fact{GroupID: router.Context(r).Env["GroupID"].(uint)}} if err := Request(&views.Fact{Fact: args.Fact}, r); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"fact": err.Error()}, http.StatusBadRequest) return } var ( contactClient = rpcClient(r, "ContactClient") reply = models.FactReply{} ) err := contactClient.Call("Fact.Create", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } args.Fact = reply.Fact err = contactClient.Call("Search.IndexFact", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Fact{Fact: reply.Fact}, http.StatusOK) }
// CreateRefvalue calls the Create method from Forms via RPC (Refvalue client). Returns results via jsonapi. func CreateRefvalue(w http.ResponseWriter, r *http.Request) { var ( args = models.RefvalueArgs{Refvalue: &models.Refvalue{GroupID: router.Context(r).Env["GroupID"].(uint)}} ) /* CID, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } args.Refvalue.FormID = uint(CID)*/ if err := Request(&views.Refvalue{Refvalue: args.Refvalue}, r); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"refvalue": err.Error()}, http.StatusBadRequest) return } var ( formClient = rpcClient(r, "FormClient") reply = models.RefvalueReply{} ) err := formClient.Call("Refvalue.Create", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Refvalue{Refvalue: reply.Refvalue}, http.StatusOK) }
// RetrieveGroup calls the GroupSQL First method and returns the results func RetrieveGroup(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } var ( g = models.Group{} db = getDB(r) groupStore = models.GroupStore(db) ) if err = groupStore.First(&g, uint(id)); err != nil { if err == sql.ErrNoRows { Fail(w, r, nil, http.StatusNotFound) return } logs.Error(err) Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Group{Group: &g}, http.StatusOK) }
// DeleteGroup calls the GroupSQL Delete method and returns the results func DeleteGroup(w http.ResponseWriter, r *http.Request) { var ( groupID int err error ) if groupID, err = strconv.Atoi(router.Context(r).Param("id")); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } var ( db = getDB(r) groupStore = models.GroupStore(db) g = &models.Group{ID: uint(groupID)} ) if err = groupStore.Delete(g); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } w.Header().Set("Content-Type", "text/plain") Success(w, r, nil, http.StatusNoContent) }
// UpdateGroup calls the GroupSQL Save method and returns the results func UpdateGroup(w http.ResponseWriter, r *http.Request) { var ( groupID int err error ) if groupID, err = strconv.Atoi(router.Context(r).Param("id")); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } var ( db = getDB(r) groupStore = models.GroupStore(db) g = &models.Group{ID: uint(groupID)} ) if err = groupStore.First(g, g.ID); err != nil { Fail(w, r, map[string]interface{}{"group": err.Error()}, http.StatusBadRequest) return } if err = Request(&views.Group{Group: g}, r); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"group": err.Error()}, http.StatusBadRequest) return } if err = groupStore.Save(g); err != nil { logs.Error(err) Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Group{Group: g}, http.StatusOK) }
// CreateForm calls the Create method from Forms via RPC (Form client) and then calls the Index method from Forms via RPC (Search client). Returns results via jsonapi. func CreateForm(w http.ResponseWriter, r *http.Request) { var ( args = models.FormArgs{Form: &models.Form{GroupID: router.Context(r).Env["GroupID"].(uint)}} ) if err := Request(&views.Form{Form: args.Form}, r); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"form": err.Error()}, http.StatusBadRequest) return } var ( formClient = rpcClient(r, "FormClient") reply = models.FormReply{} ) err := formClient.Call("Form.Create", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } //rep := models.FormReply{} args.Form = reply.Form Success(w, r, views.Form{Form: reply.Form}, http.StatusOK) }
// Returns the group informations using his authentication token. Calls Oauth2 via HTTP. Returns results via jsonapi. func RetrieveGroup(w http.ResponseWriter, r *http.Request) { ID := router.Context(r).Env["GroupID"].(uint) path := fmt.Sprintf("/groups/%d", ID) body, _ := Service(GetMethod, r, "OAuth2", path) resp := make(map[string]interface{}) if err := json.Unmarshal(body, &resp); err != nil { logs.Error(err) Fail(w, r, map[string]string{"Authentication": "Could not join the server"}, http.StatusBadRequest) return } if resp["error"] != nil { Fail(w, r, resp["error_description"], http.StatusBadRequest) } else { resp = resp["data"].(map[string]interface{}) resp = resp["group"].(map[string]interface{}) //UID := int64(resp["id"].(float64)) GID := uint(resp["id"].(float64)) NAME := sPtr(resp["name"].(string)) Date := time.Now() if resp["endofcampain"] != nil { datecampain := resp["endofcampain"].(string) Date, _ = time.Parse(time.RFC3339, datecampain) } g := usermodels.Group{ID: GID, Name: NAME, Endofcampain: &Date} // Success(w, r, userviews.Group{Group: &g}, http.StatusOK) //g := usermodels.Group{ID: GID, Name: NAME} SuccessOKOr404(w, r, userviews.Group{Group: &g}) } }
// Apply is a middleware which make the app context available to the // requests handlers through the router. Obviously, this stands for // iogo-framework/router. func (app *Application) Apply(h http.Handler) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { router.Context(r).Env["Application"] = app h.ServeHTTP(w, r) } return http.HandlerFunc(fn) }
// Prepares the request with the provided infos and a custom body func ServiceBody(method string, r *http.Request, service string, path string, bodyType string, body []byte) ([]byte, error) { s := router.Context(r).Env["Application"].(*application.Application).Components[service].(settings.Server) urlstr := fmt.Sprintf("http://%s:%d%s", s.Host, s.Port, path) fn := func(r *http.Request) { r.SetBasicAuth("1234", "aabbccdd") r.Header.Add("Content-Type", bodyType) } return request(method, urlstr, fn, bytes.NewReader(body)) }
// DeleteFact calls the Delete method from Contacts via RPC (Fact client). Returns results via jsonapi. func DeleteFact(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(router.Context(r).Param("fact_id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"fact_id": "not integer"}, http.StatusBadRequest) return } var ( contactClient = rpcClient(r, "ContactClient") args = models.FactArgs{Fact: &models.Fact{GroupID: router.Context(r).Env["GroupID"].(uint)}} reply = models.FactReply{} ) args.Fact.ID = uint(id) err = contactClient.Call("Fact.Delete", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, nil, http.StatusNoContent) }
// UpdateNote calls the Update method from Contacts via RPC (Note client). Returns results via jsonapi. func UpdateNote(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } note_id, err := strconv.Atoi(router.Context(r).Param("note_id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"note_id": "not integer"}, http.StatusBadRequest) return } var ( args = models.NoteArgs{Note: &models.Note{GroupID: router.Context(r).Env["GroupID"].(uint), ContactID: uint(id)}} ) if err := Request(&views.Note{Note: args.Note}, r); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"note": err.Error()}, http.StatusBadRequest) return } var ( contactClient = rpcClient(r, "ContactClient") reply = models.NoteReply{} ) args.Note.ID = uint(note_id) err = contactClient.Call("Note.Create", args, &reply) if err != nil { logs.Debug(err) Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Note{Note: reply.Note}, http.StatusOK) }
// RetrieveRefvalue calls the Retrieve method from Forms via RPC (Refvalue client). Returns results via jsonapi. func RetrieveRefvalue(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(router.Context(r).Param("id")) if err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"id": "not integer"}, http.StatusBadRequest) return } var ( formClient = rpcClient(r, "FormClient") args = models.RefvalueArgs{ Refvalue: &models.Refvalue{ID: uint(id), GroupID: router.Context(r).Env["GroupID"].(uint)}, } reply = models.RefvalueReply{} ) err = formClient.Call("Refvalue.Retrieve", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } SuccessOKOr404(w, r, views.Refvalue{Refvalue: reply.Refvalue}) }
// Generates a authentication token, stores it in a Redis instance under a new id and stores the id in a cookie on the user's browser to allow the gateway to later retrieve the token from the cookie and authenticate the user func Session(w http.ResponseWriter, req *http.Request) { req.ParseForm() if req.FormValue("username") != "" && req.FormValue("password") != "" { // Perform an OAuth "Resource Owner Password Credentials Grant" req.Form.Add("grant_type", "password") body, err := ServiceBody(PostMethod, req, "OAuth2", "/oauth2/token", "application/x-www-form-urlencoded", []byte(req.Form.Encode())) if err != nil { logs.Error(err) return } // TODO: Check http status for errors access := new(components.AccessData) if err := json.Unmarshal(body, access); err != nil { logs.Error(err) jsonapi.Error(w, req, err.Error(), http.StatusBadRequest) return } if access.AccessToken == "" { var err = errors.New("wrong identifiers") logs.Error(err) jsonapi.Fail(w, req, err.Error(), http.StatusBadRequest) return } session := &components.Session{ ID: strings.TrimRight(base64.StdEncoding.EncodeToString(uuid.NewRandom()), "="), AccessToken: access.AccessToken, RefreshToken: access.RefreshToken, ExpiresIn: access.ExpiresIn, } app := router.Context(req).Env["Application"].(*application.Application) store := app.Components["Redis"].(*components.RedisStore) if err := store.Save(session); err != nil { logs.Error(err) jsonapi.Error(w, req, err.Error(), http.StatusBadRequest) return } cookie := &http.Cookie{Name: "SID", Value: session.ID, Expires: time.Now().Add(356 * 24 * time.Hour)} http.SetCookie(w, cookie) jsonapi.Success(w, req, "", http.StatusOK) fmt.Println(cookie) } else { jsonapi.Error(w, req, "Bad Request", http.StatusBadRequest) } }
// CreateContact calls the Create method from Contacts via RPC (Contact client) and then calls the Index method from Contacts via RPC (Search client). Returns results via jsonapi. func CreateContact(w http.ResponseWriter, r *http.Request) { var ( args = models.ContactArgs{Contact: &models.Contact{GroupID: router.Context(r).Env["GroupID"].(uint)}} //dataGEO = models.Ban{} ) if err := Request(&views.Contact{Contact: args.Contact}, r); err != nil { logs.Error(err) Fail(w, r, map[string]interface{}{"contact": err.Error()}, http.StatusBadRequest) return } var ( contactClient = rpcClient(r, "ContactClient") reply = models.ContactReply{} ) var coordonnees [2]string coordonnees = Geoloc(&args) if coordonnees[0] == "noresponse" { err := errors.New("noresponse") Error(w, r, err.Error(), http.StatusBadRequest) return } args.Contact.Address.Latitude = coordonnees[0] args.Contact.Address.Longitude = coordonnees[1] err := contactClient.Call("Contact.Create", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } rep := models.ContactReply{} args.Contact = reply.Contact err = contactClient.Call("Search.Index", args, &rep) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Contact{Contact: reply.Contact}, http.StatusOK) }
// RetrieveFactcollection calls the RetrieveCollection method from Contacts via RPC (Fact client). Returns results via jsonapi. func RetrieveFactCollection(w http.ResponseWriter, r *http.Request) { var ( contactClient = rpcClient(r, "ContactClient") args = models.FactArgs{Fact: &models.Fact{GroupID: router.Context(r).Env["GroupID"].(uint)}} reply = models.FactReply{} ) err := contactClient.Call("Fact.RetrieveCollection", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } if reply.Facts == nil { reply.Facts = make([]models.Fact, 0) } Success(w, r, views.Facts{Facts: reply.Facts}, http.StatusOK) }
// RetrieveFormcollectionByTypeAndName calls the RetrieveCollectionByTypeAndName method from Forms via RPC (Form client). Returns results via jsonapi. func RetrieveFormCollectionByTypeAndName(w http.ResponseWriter, r *http.Request) { var ( formClient = rpcClient(r, "FormClient") args = models.FormArgs{Form: &models.Form{GroupID: router.Context(r).Env["GroupID"].(uint), Type: router.Context(r).Param("type"), Name: router.Context(r).Param("name")}} reply = models.FormReply{} ) err := formClient.Call("Form.RetrieveCollectionByTypeAndName", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } if reply.Forms == nil { reply.Forms = make([]models.Form, 0) } Success(w, r, views.Forms{Forms: reply.Forms}, http.StatusOK) }
func ForwardElastic(w http.ResponseWriter, r *http.Request) { u, err := url.Parse(fmt.Sprintf("%s%s%s", "http://", r.Host, r.URL)) if err != nil { logs.Debug(err) return } app := router.Context(r).Env["Application"].(*application.Application) elasticsearch := app.Components["Elasticsearch"].(string) path := strings.TrimLeft(r.URL.String(), "/elasticsearch") urlFinal := fmt.Sprintf("%s://%s/%s", u.Scheme, elasticsearch, path) logs.Debug("%s : %s", r.Method, urlFinal) client := &http.Client{} newReq, err := http.NewRequest(r.Method, urlFinal, r.Body) newReq.Header = r.Header resp, err := client.Do(newReq) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } tradBody := string(body) jsonBody := fmt.Sprintf("{\"status\":\"success\",\"data\":%s}", tradBody) encodedBody := []byte(jsonBody) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(encodedBody) }
// Deletes the cookie on the user's browser, allows him to logout func DeleteSession(w http.ResponseWriter, req *http.Request) { cookie, err := req.Cookie("SID") if err == nil { app := router.Context(req).Env["Application"].(*application.Application) store := app.Components["Redis"].(*components.RedisStore) err := store.Delete(cookie.Value) if err != nil { logs.Error(err) jsonapi.Error(w, req, err.Error(), http.StatusBadRequest) return } cookie := &http.Cookie{Name: "SID", Value: cookie.Value, Expires: time.Now()} http.SetCookie(w, cookie) jsonapi.Success(w, req, "", http.StatusOK) logs.Debug("Cookie deleted") } else { logs.Error(err) } }
// Returns the user informdataations using his authentication token. Calls Oauth2 via HTTP. Returns results via jsonapi. func RetrieveSelf(w http.ResponseWriter, r *http.Request) { ID := router.Context(r).Env["UserID"].(uint) path := fmt.Sprintf("/users/%d", ID) body, _ := Service(GetMethod, r, "OAuth2", path) resp := make(map[string]interface{}) if err := json.Unmarshal(body, &resp); err != nil { logs.Error(err) Fail(w, r, map[string]string{"Authentication": "Could not join the server"}, http.StatusBadRequest) return } if resp["error"] != nil { Fail(w, r, resp["error_description"], http.StatusBadRequest) } else { resp = resp["data"].(map[string]interface{}) resp = resp["user"].(map[string]interface{}) UID := int64(resp["id"].(float64)) GID := uint(resp["group_id"].(float64)) u := usermodels.User{ID: UID, GroupID: GID, Mail: sPtr(resp["Mail"].(string)), Firstname: sPtr(resp["firstname"].(string)), Surname: sPtr(resp["surname"].(string))} SuccessOKOr404(w, r, userviews.User{User: &u}) } }
// CreateMission calls the Create method from Contacts via RPC (Mission client). Returns results via jsonapi. func CreateMission(w http.ResponseWriter, r *http.Request) { var ( args = models.MissionArgs{Mission: &models.Mission{GroupID: router.Context(r).Env["GroupID"].(uint)}} ) if err := Request(&views.Mission{Mission: args.Mission}, r); err != nil { logs.Debug(err) Fail(w, r, map[string]interface{}{"mission": err.Error()}, http.StatusBadRequest) return } var ( contactClient = rpcClient(r, "ContactClient") reply = models.MissionReply{} ) err := contactClient.Call("Mission.Create", args, &reply) if err != nil { Error(w, r, err.Error(), http.StatusInternalServerError) return } Success(w, r, views.Mission{Mission: reply.Mission}, http.StatusOK) }
// RetrieveContactcollectionViaElastic calls the RetrieveContacts method from Contacts via RPC (Search client). Returns results via jsonapi. func RetrieveContactCollectionViaElastic(w http.ResponseWriter, r *http.Request) { var ( contactClient = rpcClient(r, "ContactClient") args = models.SearchArgs{} reply = models.SearchReply{} ) args.Search = new(models.Search) args.Search.Query = router.Context(r).Param("query") err := contactClient.Call("Search.RetrieveContacts", args, &reply) if err != nil { logs.Error(err) Error(w, r, err.Error(), http.StatusInternalServerError) return } if reply.Contacts == nil { reply.Contacts = make([]models.Contact, 0) } Success(w, r, views.Contacts{Contacts: reply.Contacts}, http.StatusOK) }