// Compares the request's origin with a list of defined origins and allows it if one of them matches func AllowKnownOrigin(w http.ResponseWriter, req *http.Request) { headerOrigin := req.Header.Get("Origin") if headerOrigin != "" { addr := strings.Split(req.RemoteAddr, ":")[0] for _, srcOrigin := range KnownOrigins { if srcOrigin == headerOrigin { logs.Debug("Match : %s - %s", srcOrigin, headerOrigin) w.Header().Set("Access-Control-Allow-Origin", headerOrigin) return } originAddr, err := net.LookupHost(srcOrigin) var origin string if err == nil { origin = originAddr[0] } else { origin = srcOrigin } if origin == addr { logs.Debug("Match : %s - %s", addr, origin) w.Header().Set("Access-Control-Allow-Origin", headerOrigin) return } } } w.Header().Set("Access-Control-Allow-Origin", "https://cloud.quorumapps.com") }
// Index indexes a contact into elasticsearch func index(Contact *models.Contact, s *elastic.Client) error { id := strconv.Itoa(int(Contact.ID)) if id == "" { logs.Error("id is nil") return errors.New("id is nil") } if Contact.Address.Longitude == "null" || Contact.Address.Latitude == "null" { logs.Debug("Could not index contact %s", id) return nil } if Contact.Address.Latitude != "" && Contact.Address.Longitude != "" { Contact.Address.Location = fmt.Sprintf("%s,%s", Contact.Address.Latitude, Contact.Address.Longitude) } _, err := s.Index(). Index("contacts"). Type("contact"). Id(id). BodyJson(Contact). Do() if err != nil { logs.Critical(err) return err } logs.Debug("Contact %s indexed", id) return nil }
// 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) }
// 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) }
func createFact(contact *models.Contact, client *elastic.Client, db *gorm.DB) error { Fact := &models.Fact{} Fact.GroupID = 1 Fact.Action.Name = "init" Fact.Action.Pitch = "initialise la table de faits" Fact.Action.TypeData = "aucune" Fact.Status = "init" Fact.ContactID = contact.ID Fact, err := storeFact(Fact, db) if err != nil { return err } if Fact.Contact.ID == 0 { logs.Debug("Contact %d didn't exist. Fact %d may therefore be incorrect", contact.ID, Fact.ID) } err = indexFact(*Fact, client) if err != nil { return err } logs.Debug("Fact %d created and indexed", Fact.ID) return nil }
// 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) }
// 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) }
// 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) }
// 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) }
func serve(ctx *cli.Context) error { var err error var config settings.Config if ctx.String("config") != "" { config, err = settings.Parse(ctx.String("config")) if err != nil { logs.Error(err) } } if config.Debug() { logs.Level(logs.DebugLevel) } dialect, args, err := config.SqlDB() if err != nil { logs.Critical(err) os.Exit(1) } logs.Debug("database type: %s", dialect) var app = application.New() if app.Components["DB"], err = databases.InitGORM(dialect, args); err != nil { logs.Critical(err) os.Exit(1) } logs.Debug("connected to %s", args) if config.Migrate() { app.Components["DB"].(*gorm.DB).AutoMigrate(models.Models()...) logs.Debug("database migrated successfully") } app.Components["Templates"] = views.Templates() // app.Components["Mux"] = router.New() app.Components["Mux"] = gojimux.New() if config.Debug() { app.Use(router.Logger) } app.Use(app.Apply) app.Get("/users/register", controllers.Register) app.Post("/users/auth", controllers.Auth) app.Post("/users/register", controllers.Register) server, err := config.Server() if err != nil { logs.Critical(err) os.Exit(1) } return app.Serve(server.String()) }
// 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) }
// Returns a storage session func (s *RedisStorage) LoadAccess(code string) (*osin.AccessData, error) { logs.Debug("LoadAccess: %s", code) d_map, err := s.client.HGetAllMap(code).Result() if len(d_map) == 0 || err != nil { return nil, errors.New("Authorize not found") } client, err := s.getClient(d_map["client"]) if err != nil { return nil, err } expires_in, _ := strconv.Atoi(d_map["expires_in"]) created_at := new(time.Time) created_at.UnmarshalBinary([]byte(d_map["created_at"])) d := &osin.AccessData{ Client: client, ExpiresIn: int32(expires_in), Scope: d_map["scope"], RedirectUri: d_map["redirect_uri"], CreatedAt: *created_at, UserData: d_map["user_data"], } return d, nil }
// Saves a new storage session func (s *RedisStorage) SaveAccess(data *osin.AccessData) error { logs.Debug("SaveAccess: %s", data.AccessToken) s.access[data.AccessToken] = data if data.RefreshToken != "" { s.refresh[data.RefreshToken] = data.AccessToken } binary, _ := data.CreatedAt.MarshalBinary() s.client.HMSet(data.AccessToken, "client", data.Client.GetId(), "expires_in", strconv.Itoa(int(data.ExpiresIn)), "scope", data.Scope, "redirect_uri", data.RedirectUri, "created_at", string(binary), "user_data", data.UserData.(string), ).Result() s.client.Expire(data.AccessToken, time.Duration(data.ExpiresIn)*time.Second).Result() // s.client.Expire(data.AccessToken, 10*time.Second).Result() if data.RefreshToken != "" { s.client.Set(data.RefreshToken, data.AccessToken, time.Duration(data.ExpiresIn)*time.Second).Result() } return nil }
// 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) }
func printEnd(reqID string, w mutil.WriterProxy, dt time.Duration) { var buf bytes.Buffer if reqID != "" { cW(&buf, bBlack, "[%s] ", reqID) } buf.WriteString("Returning ") status := w.Status() if status < 200 { cW(&buf, bBlue, "%03d", status) } else if status < 300 { cW(&buf, bGreen, "%03d", status) } else if status < 400 { cW(&buf, bCyan, "%03d", status) } else if status < 500 { cW(&buf, bYellow, "%03d", status) } else { cW(&buf, bRed, "%03d", status) } buf.WriteString(" in ") if dt < 500*time.Millisecond { cW(&buf, nGreen, "%s", dt) } else if dt < 5*time.Second { cW(&buf, nYellow, "%s", dt) } else { cW(&buf, nRed, "%s", dt) } logs.Debug(buf.String()) }
// Creates a new user func Register(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { req.ParseForm() passwordHash, err := bcrypt.GenerateFromPassword([]byte(req.FormValue("password")), bcrypt.DefaultCost) if err != nil { panic(err) } u := &models.User{ Firstname: sPtr(req.FormValue("firstname")), Surname: sPtr(req.FormValue("surname")), Mail: sPtr(req.FormValue("mail")), Password: sPtr(string(passwordHash)), } errs := u.Validate() if len(errs) > 0 { logs.Debug(errs) return } var store = models.UserStore(getDB(req)) err = store.Save(u) if err != nil { logs.Error(err) return } } templates := getTemplates(req) if err := templates["users/register"].ExecuteTemplate(w, "base", nil); err != nil { logs.Error(err) } }
// 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) }
// 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) }
func UpdateUser(w http.ResponseWriter, req *http.Request) { //logs.Debug("on rentre dans RegisterUser") req.ParseForm() if req.FormValue("mail") != "" && req.FormValue("password") != "" { // Perform an OAuth "Resource Owner Password Credentials Grant" req.Form.Add("grant_type", "password") body, err := ServiceBody(PostMethod, req, "OAuth2", "/users/update", "application/x-www-form-urlencoded", []byte(req.Form.Encode())) if err != nil { logs.Error(err) jsonapi.Error(w, req, err.Error(), http.StatusInternalServerError) return } else { logs.Debug("on passe successfull dans UpdateUser de Gateway/controllers/session.go") } // Check http status for errors var t StructRegisterUser err = json.Unmarshal(body, &t) if err != nil { } else { jsonapi.Error(w, req, t.Message, http.StatusBadRequest) } } }
// 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) }
// 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) }
//Find the last indexed Contact's ID func findID(s *elastic.Client) (int, error) { termQuery := elastic.NewMatchAllQuery() searchResult, err := s.Search(). Index("contacts"). Query(&termQuery). Fields("_timestamp"). Sort("_timestamp", false). Size(1). Pretty(true). Do() if err != nil { logs.Critical(err) return 0, err } var ID int if searchResult.Hits != nil { for _, hit := range searchResult.Hits.Hits { ID, err = strconv.Atoi(hit.Id) if err != nil { return 0, err } } } else { logs.Debug("No results, ID is 1") return 1, nil } return ID, nil }
func (s *RedisStorage) LoadRefresh(code string) (*osin.AccessData, error) { logs.Debug("LoadRefresh: %s", code) d, err := s.client.Get(code).Result() if err != nil { return nil, errors.New("Authorize not found") } return s.LoadAccess(d) }
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) }
// Returns a client from it's id func (s *RedisStorage) GetClient(id string) (osin.Client, error) { logs.Debug("GetClientDatabase: %s", id) if c, ok := s.clients[id]; ok { s.client.HMSet(id, "secret", c.GetSecret(), "redirect_uri", c.GetRedirectUri(), ) return c, nil } return nil, errors.New("Client not found") }
// 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) }
func printStart(reqID string, r *http.Request) { var buf bytes.Buffer if reqID != "" { cW(&buf, bBlack, "[%s] ", reqID) } buf.WriteString("Started ") cW(&buf, bMagenta, "%s ", r.Method) cW(&buf, nBlue, "%q ", r.URL.String()) buf.WriteString("from ") buf.WriteString(r.RemoteAddr) logs.Debug(buf.String()) }
// Saves a new client func (s *RedisStorage) SaveAuthorize(data *osin.AuthorizeData) error { logs.Debug("SaveAuthorize: %s", data.Code) binary, _ := data.CreatedAt.MarshalBinary() s.client.HMSet(data.Code, "client", data.Client.GetId(), "expires_in", strconv.Itoa(int(data.ExpiresIn)), "scope", data.Scope, "redirect_uri", data.RedirectUri, "state", data.State, "created_at", string(binary), ).Result() s.client.Expire(data.Code, time.Duration(data.ExpiresIn)*time.Second).Result() s.client.Expire(data.Client.GetId(), time.Duration(data.ExpiresIn)*time.Second).Result() return nil }