func (talk *Talk) GetTalkByUsersId() bool { talk1 := new(Talk) talk2 := new(Talk) curs, _ := r.Table("talks"). Filter(r.Row.Field("UserIdX").Eq(talk.UserIdX)). Filter(r.Row.Field("UserIdY").Eq(talk.UserIdY)). Run(api.Sess) curs2, _ := r.Table("talks"). Filter(r.Row.Field("UserIdX").Eq(talk.UserIdY)). Filter(r.Row.Field("UserIdY").Eq(talk.UserIdX)). Run(api.Sess) curs.One(&talk1) curs2.One(&talk2) if len(talk1.Id) == 0 && len(talk2.Id) == 0 { return false } if talk1.Id != "" { talk.copyTalk(talk1) } else { talk.copyTalk(talk2) } return true }
func (place *Place) getListPlace(getList GetListPlace) ListPlace { list := ListPlace{} var curs *r.Cursor if strings.Compare(getList.Filter, "") == 0 && strings.Compare(getList.Venue, "") == 0 { curs, _ = r.Table("places").Filter(r.Row.Field("Validated").Eq(true)).Slice(getList.Offset, getList.Offset+getList.Limit).OrderBy("-PostNb").Run(api.Sess) } else if strings.Compare(getList.Filter, "") != 0 && strings.Compare(getList.Venue, "") == 0 { curs, _ = r.Table("places").Filter(r.Row.Field("Validated").Eq(true)).Filter(func(customer r.Term) interface{} { return customer.Field(getList.Filter).Downcase().Match("^" + strings.ToLower(getList.FilterValue)) }).Slice(getList.Offset, getList.Offset+getList.Limit).OrderBy("-PostNb").Run(api.Sess) } else if strings.Compare(getList.Filter, "") == 0 && strings.Compare(getList.Venue, "") != 0 { curs, _ = r.Table("places").Filter(r.Row.Field("Validated").Eq(true)).Filter(r.Row.Field("Type").Eq(getList.Venue)).Slice(getList.Offset, getList.Offset+getList.Limit).OrderBy("-PostNb").Run(api.Sess) } else if strings.Compare(getList.Filter, "") != 0 && strings.Compare(getList.Venue, "") != 0 { curs, _ = r.Table("places").Filter(r.Row.Field("Validated").Eq(true)).Filter(func(customer r.Term) interface{} { return customer.Field(getList.Filter).Downcase().Match("^" + strings.ToLower(getList.FilterValue)) }).Filter(r.Row.Field("Type").Eq(getList.Venue)).Slice(getList.Offset, getList.Offset+getList.Limit).OrderBy("-PostNb").Run(api.Sess) } curs.All(&list.Places) return list }
func TestMain(m *testing.M) { var session *r.Session var err error c, err := dockertest.ConnectToRethinkDB(20, time.Millisecond*500, func(url string) bool { if session, err = r.Connect(r.ConnectOpts{Address: url, Database: "hydra"}); err != nil { return false } else if _, err = r.DBCreate("hydra").RunWrite(session); err != nil { logrus.Printf("Database exists: %s", err) return false } else if _, err = r.TableCreate("hydra_authorize_code").RunWrite(session); err != nil { logrus.Printf("Could not create table: %s", err) return false } else if _, err = r.TableCreate("hydra_id_sessions").RunWrite(session); err != nil { logrus.Printf("Could not create table: %s", err) return false } else if _, err = r.TableCreate("hydra_access_token").RunWrite(session); err != nil { logrus.Printf("Could not create table: %s", err) return false } else if _, err = r.TableCreate("hydra_implicit").RunWrite(session); err != nil { logrus.Printf("Could not create table: %s", err) return false } else if _, err = r.TableCreate("hydra_refresh_token").RunWrite(session); err != nil { logrus.Printf("Could not create table: %s", err) return false } rethinkManager = &FositeRehinkDBStore{ Session: session, AuthorizeCodesTable: r.Table("hydra_authorize_code"), IDSessionsTable: r.Table("hydra_id_sessions"), AccessTokensTable: r.Table("hydra_access_token"), ImplicitTable: r.Table("hydra_implicit"), RefreshTokensTable: r.Table("hydra_refresh_token"), AuthorizeCodes: make(RDBItems), IDSessions: make(RDBItems), AccessTokens: make(RDBItems), Implicit: make(RDBItems), RefreshTokens: make(RDBItems), } rethinkManager.Watch(context.Background()) time.Sleep(500 * time.Millisecond) return true }) if session != nil { defer session.Close() } if err != nil { logrus.Fatalf("Could not connect to database: %s", err) } clientManagers["rethink"] = rethinkManager retCode := m.Run() c.KillRemove() os.Exit(retCode) }
func (user *User) createUserFacebook(request *restful.Request, response *restful.Response) { if user.getUserFacebookWithAccessToken(request.HeaderParameter("facebooktoken")) == false { response.InternalServerError() helpers.PrintLog(request, response, user.Name) return } newUser := new(User) //Facebook's data newUser.FacebookId = user.FacebookId newUser.UrlPicture = user.UrlPicture newUser.Name = user.Name isUserExist := newUser.getUserByFacebookId() if isUserExist == false { //user newUser.Group = 0 newUser.CreateDate = time.Now() newUser.Email = "" newUser.Banish = false } //Session newUser.CreateDateToken = time.Now() newUser.ExpireDateToken = time.Now().AddDate(0, 0, 15) newUser.Token = uuid.New() var resp r.WriteResponse var err error //insert if isUserExist == false { resp, err = r.Table("users").Insert(newUser).RunWrite(api.Sess) //update } else { _, err = r.Table("users").Get(newUser.Id).Update(newUser).RunWrite(api.Sess) } if err != nil { response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) helpers.PrintLog(request, response, user.Name) return } //if user has been insert, we got ID if isUserExist == false { newUser.Id = resp.GeneratedKeys[0] } response.WriteHeaderAndEntity(http.StatusCreated, newUser) helpers.PrintLog(request, response, user.Name) return }
func (m DefaultManager) SaveAccount(account *auth.Account) error { var ( hash string eventType string ) if account.Password != "" { h, err := auth.Hash(account.Password) if err != nil { return err } hash = h } // check if exists; if so, update acct, err := m.Account(account.Username) if err != nil && err != ErrAccountDoesNotExist { return err } // update if acct != nil { updates := map[string]interface{}{ "first_name": account.FirstName, "last_name": account.LastName, "roles": account.Roles, } if account.Password != "" { updates["password"] = hash } if _, err := r.Table(tblNameAccounts).Filter(map[string]string{"username": account.Username}).Update(updates).RunWrite(m.session); err != nil { return err } eventType = "update-account" } else { account.Password = hash if _, err := r.Table(tblNameAccounts).Insert(account).RunWrite(m.session); err != nil { return err } eventType = "add-account" } m.logEvent(eventType, fmt.Sprintf("username=%s", account.Username), []string{"security"}) return nil }
func handleChangeNotification(socket *websocket.Conn, userID string, err chan string) { res, errr := r.Table("notifications"). Filter(r.Row.Field("UserId"). Eq(userID)). Changes(). Run(api.Sess) var value HandleChange if errr != nil { err <- errr.Error() } for res.Next(&value) { var notif api.Notification var simpleNotif api.WebSocketNotification mapstructure.Decode(value.NewVal, ¬if) if notif.Id == "" { mapstructure.Decode(value.OldVal, ¬if) simpleNotif.OldVal = true } else { simpleNotif.OldVal = false } simpleNotif.Title = "notification" simpleNotif.Type = notif.Type simpleNotif.Name = notif.Name simpleNotif.UserIdFrom = notif.UserIdFrom simpleNotif.IdLink = notif.IdLink simpleNotif.CreatedAt = notif.CreatedAt errr := socket.WriteJSON(simpleNotif) if errr != nil { err <- errr.Error() } } }
func (user *User) createUser(request *restful.Request, response *restful.Response) { newUser := new(User) //user newUser.Email = user.Email newUser.Name = user.Name newUser.CreateDate = time.Now() newUser.Group = 100 newUser.FacebookId = "" newUser.UrlPicture = "" newUser.Banish = false //encrypt password newUser.Password = helpers.NewCryptPasswd([]byte(user.Password)) //session newUser.CreateDateToken = time.Now() newUser.ExpireDateToken = time.Now().AddDate(0, 0, 15) newUser.Token = uuid.New() resp, err := r.Table("users").Insert(newUser).RunWrite(api.Sess) if err != nil { response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) helpers.PrintLog(request, response, user.Name) return } newUser.Id = resp.GeneratedKeys[0] newUser.Password = "" response.WriteHeaderAndEntity(http.StatusCreated, newUser) }
func (like *Like) getLikesByUserId(searchWithPost bool, limit int, offset int) interface{} { var list []Like var likelist LikeList curs, err := r.Table("likes"). Filter(r.Row.Field("UserId").Eq(like.user.Id)). Slice(offset, offset+limit). Run(api.Sess) if err != nil && searchWithPost == true { return LikeAndPostList{} } if err != nil && searchWithPost == false { return likelist } curs.All(&list) defer curs.Close() if searchWithPost == true { likeAndPostList := LikeAndPostList{} var liste []LikeAndPost for _, aLike := range list { post := post.Post{Id: aLike.PostId} post.GetPostById() likeAndPost := LikeAndPost{Like: aLike, Post: post} liste = append(liste, likeAndPost) } likeAndPostList.List = liste return likeAndPostList } likelist.List = list return likelist }
func (match *Match) createMatch(request *restful.Request, response *restful.Response) { newMatch := new(Match) newMatch.CreateAt = time.Now() newMatch.PlaceId = match.post.PlaceId newMatch.PostId = match.post.Id newMatch.UserIdX = match.user.Id newMatch.UserImageX = match.user.UrlPicture newMatch.UserNameX = match.user.Name newMatch.UserIdY = match.post.UserId newMatch.UserNameY = match.post.UserName newMatch.Validated = false resp, err := r.Table("matchs").Insert(newMatch).RunWrite(api.Sess) if err != nil { response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) helpers.PrintLog(request, response, match.user.Name) return } go func() { notif := notification.SetMatchReceive() notif.UserId = match.post.UserId notif.UserIdFrom = match.user.Id notif.IdThing = resp.GeneratedKeys[0] notif.Name = match.user.Name notif.IdLink = match.post.Id notif.CreateNotification() }() newMatch.Id = resp.GeneratedKeys[0] response.WriteHeaderAndEntity(http.StatusCreated, newMatch) helpers.PrintLog(request, response, match.user.Name) }
func (message *Message) createMessageWithContent(request *restful.Request, response *restful.Response) { msg := new(Message) msg.Content = message.Content msg.CreatedAt = time.Now() msg.FromUserId = message.user.Id msg.TalkId = message.talk.Id msg.Read = false if message.talk.UserIdX == message.user.Id { msg.ToUserId = message.talk.UserIdY } else { msg.ToUserId = message.talk.UserIdX } resp, err := r.Table("messages").Insert(msg).RunWrite(api.Sess) if err != nil { helpers.PrintLog(request, response, message.user.Name) response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) return } msg.Id = resp.GeneratedKeys[0] message.talk.UpdateLastMessageDate(message.user.Id, message.Content) response.WriteHeaderAndEntity(http.StatusCreated, msg) helpers.PrintLog(request, response, message.user.Name) }
func (place *Place) createPlace(request *restful.Request, response *restful.Response) { place.Lat = 0 place.Lng = 0 place.PostNb = 0 place.ValidatedAt = *new(time.Time) place.Validated = false place.CreateAt = time.Now() place.UserId = place.user.Id place.Id = *new(string) request.Request.ParseMultipartForm(32 << 20) mpf, hdr, _ := request.Request.FormFile("image") ext := filepath.Ext(hdr.Filename) if helpers.CheckFileExtension(ext) == false { errors := api.Error{} errors.ListErrors = append(errors.ListErrors, "Only .jpg, .jpeg or .png are authorized.") response.WriteHeaderAndEntity(406, errors) helpers.PrintLog(request, response, place.user.Name) return } place.Image = helpers.GenerateHash(50) + ext go helpers.PutFile("assets/Images/"+place.Image, mpf) resp, err := r.Table("places").Insert(place).RunWrite(api.Sess) if err != nil { response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) return } place.Id = resp.GeneratedKeys[0] response.WriteHeaderAndEntity(http.StatusCreated, place) helpers.PrintLog(request, response, place.user.Name) }
func (talk *Talk) RemoveTalk() error { if talk.GetTalkByUsersId() == true { _, err := r.Table("talks").Get(talk.Id).Delete().Run(api.Sess) return err } return nil }
func (place *Place) IncrementPostNb() error { place.PostNb += 1 _, err := r.Table("places").Get(place.Id).Update(place).RunWrite(api.Sess) return err }
func (post *Post) acceptPost(request *restful.Request, response *restful.Response) { post.Validated = true post.ValidatedAt = time.Now() if err := post.place.IncrementPostNb(); err != nil { response.WriteHeaderAndEntity(http.StatusInternalServerError, err.Error()) helpers.PrintLog(request, response, post.user.Name) return } post.IdByPlace = post.place.PostNb _, err := r.Table("posts").Get(post.Id).Update(post).RunWrite(api.Sess) if err != nil { response.WriteHeaderAndEntity(http.StatusInternalServerError, err.Error()) helpers.PrintLog(request, response, post.user.Name) return } go func() { notif := notification.SetPostAccepted() notif.UserId = post.UserId notif.UserIdFrom = post.user.Id notif.IdThing = post.Id notif.Name = post.PlaceName notif.IdLink = post.Id notif.CreateNotification() }() response.WriteHeaderAndEntity(http.StatusOK, post) helpers.PrintLog(request, response, post.user.Name) }
func (post *Post) refusePost(request *restful.Request, response *restful.Response) { _, err := r.Table("posts").Get(post.Id).Delete().Run(api.Sess) if err != nil { response.WriteHeaderAndEntity(http.StatusInternalServerError, err.Error()) helpers.PrintLog(request, response, post.user.Name) return } if post.Image != "" { helpers.RemoveFile("./assets/Images/" + post.Image) } if post.user.IsUserIsAdmin() == true { go func() { notif := notification.SetPostRefused() notif.UserId = post.UserId notif.UserIdFrom = post.user.Id notif.IdThing = post.Id notif.Name = post.PlaceName notif.IdLink = post.Id notif.CreateNotification() }() } response.WriteHeader(http.StatusOK) helpers.PrintLog(request, response, post.user.Name) }
func (place *Place) acceptPlace(request *restful.Request, response *restful.Response) { if place.getGeolocation() == false { errors := api.Error{} errors.ListErrors = append(errors.ListErrors, "We were unable to geolocate your plate") response.WriteHeaderAndEntity(500, errors) return } place.ValidatedAt = time.Now() place.Validated = true _, err := r.Table("places").Get(place.Id).Update(place).RunWrite(api.Sess) if err != nil { response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) return } go func() { notif := notification.SetPlaceAccepted() notif.UserId = place.UserId notif.UserIdFrom = place.user.Id notif.IdThing = place.Id notif.Name = place.Name notif.IdLink = place.Id notif.CreateNotification() }() response.WriteHeaderAndEntity(http.StatusOK, place) helpers.PrintLog(request, response, place.user.Name) }
func (post *Post) UpdateLikeNb(nb int) error { post.LikeNb += nb _, err := r.Table("posts").Get(post.Id).Update(post).RunWrite(api.Sess) return err }
func (place *Place) handleImage(request *restful.Request, response *restful.Response) { errors := api.Error{} request.Request.ParseMultipartForm(32 << 20) mpf, hdr, _ := request.Request.FormFile("image") ext := filepath.Ext(hdr.Filename) if helpers.CheckFileExtension(ext) == false { errors.ListErrors = append(errors.ListErrors, "Only .jpg, .jpeg or .png are authorized.") response.WriteHeaderAndEntity(406, errors) return } if strings.Compare(place.Image, "") != 0 { helpers.RemoveFile("./assets/Images/" + place.Image) } place.Image = helpers.GenerateHash(50) + ext go helpers.PutFile("assets/Images/"+place.Image, mpf) _, err := r.Table("places").Get(place.Id).Update(place).RunWrite(api.Sess) if err != nil { response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) return } response.WriteHeaderAndEntity(http.StatusOK, place) helpers.PrintLog(request, response, place.user.Name) }
func newConnectionHandler(c *config.Config, router *httprouter.Router) *connection.Handler { ctx := c.Context() h := &connection.Handler{} h.H = &herodot.JSON{} h.W = ctx.Warden h.SetRoutes(router) switch con := ctx.Connection.(type) { case *config.MemoryConnection: h.Manager = connection.NewMemoryManager() break case *config.RethinkDBConnection: con.CreateTableIfNotExists("hydra_policies") m := &connection.RethinkManager{ Session: con.GetSession(), Table: r.Table("hydra_policies"), } if err := m.ColdStart(); err != nil { logrus.Fatalf("Could not fetch initial state: %s", err) } m.Watch(context.Background()) h.Manager = m break default: panic("Unknown connection type.") } return h }
func newClientManager(c *config.Config) client.Manager { ctx := c.Context() switch con := ctx.Connection.(type) { case *config.MemoryConnection: return &client.MemoryManager{ Clients: map[string]*fosite.DefaultClient{}, Hasher: ctx.Hasher, } case *config.RethinkDBConnection: con.CreateTableIfNotExists("hydra_clients") m := &client.RethinkManager{ Session: con.GetSession(), Table: r.Table("hydra_clients"), Hasher: ctx.Hasher, } if err := m.ColdStart(); err != nil { logrus.Fatalf("Could not fetch initial state: %s", err) } m.Watch(context.Background()) return m default: panic("Unknown connection type.") } }
func newJWKHandler(c *config.Config, router *httprouter.Router) *jwk.Handler { ctx := c.Context() h := &jwk.Handler{ H: &herodot.JSON{}, W: ctx.Warden, } h.SetRoutes(router) switch con := ctx.Connection.(type) { case *config.MemoryConnection: ctx.KeyManager = &jwk.MemoryManager{} break case *config.RethinkDBConnection: con.CreateTableIfNotExists("hydra_json_web_keys") m := &jwk.RethinkManager{ Session: con.GetSession(), Keys: map[string]jose.JsonWebKeySet{}, Table: r.Table("hydra_json_web_keys"), Cipher: &jwk.AEAD{ Key: c.GetSystemSecret(), }, } if err := m.ColdStart(); err != nil { logrus.Fatalf("Could not fetch initial state: %s", err) } m.Watch(context.Background()) ctx.KeyManager = m break default: logrus.Fatalf("Unknown connection type.") } h.Manager = ctx.KeyManager return h }
func (like *Like) createLike(request *restful.Request, response *restful.Response) { newLike := new(Like) newLike.PostId = like.post.Id newLike.UserId = like.user.Id newLike.Created = time.Now() if err := like.post.UpdateLikeNb(1); err != nil { response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) return } resp, err := r.Table("likes").Insert(newLike).RunWrite(api.Sess) if err != nil { like.post.UpdateLikeNb(-1) response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) helpers.PrintLog(request, response, like.user.Name) return } if like.post.UserId != like.user.Id { go func() { notif := notification.SetLikeReceive() notif.UserId = like.post.UserId notif.UserIdFrom = like.user.Id notif.IdThing = resp.GeneratedKeys[0] notif.Name = like.user.Name notif.IdLink = like.post.Id notif.CreateNotification() }() } newLike.Id = resp.GeneratedKeys[0] response.WriteHeaderAndEntity(http.StatusCreated, newLike) helpers.PrintLog(request, response, like.user.Name) }
func (like *Like) deleteLike(request *restful.Request, response *restful.Response) { like.post.Id = like.PostId if like.post.GetPostById() == false { response.WriteHeader(http.StatusInternalServerError) helpers.PrintLog(request, response, like.user.Name) return } if err := like.post.UpdateLikeNb(-1); err != nil { response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) helpers.PrintLog(request, response, like.user.Name) return } _, err := r.Table("likes").Get(like.Id).Delete().Run(api.Sess) if err != nil { response.WriteHeaderAndEntity(http.StatusConflict, err.Error()) helpers.PrintLog(request, response, like.user.Name) return } go func() { notif := notification.SetLikeReceive() notif.IdThing = like.Id notif.UserIdFrom = like.user.Id notif.RemoveNotification() }() response.WriteHeader(http.StatusOK) helpers.PrintLog(request, response, like.user.Name) }
func (m DefaultManager) SaveEvent(event *shipyard.Event) error { if _, err := r.Table(tblNameEvents).Insert(event).RunWrite(m.session); err != nil { return err } return nil }
func connectRDB() { var err error var session *r.Session c, err := dockertest.ConnectToRethinkDB(20, time.Second, func(url string) bool { if session, err = r.Connect(r.ConnectOpts{Address: url, Database: "hydra"}); err != nil { return false } else if _, err = r.DBCreate("hydra").RunWrite(session); err != nil { log.Printf("Database exists: %s", err) return false } else if _, err = r.TableCreate("hydra_policies").RunWrite(session); err != nil { log.Printf("Could not create table: %s", err) return false } rethinkManager = &RethinkManager{ Session: session, Table: r.Table("hydra_policies"), Policies: make(map[string]Policy), } rethinkManager.Watch(context.Background()) time.Sleep(time.Second) return true }) if err != nil { log.Fatalf("Could not connect to database: %s", err) } containers = append(containers, c) managers["rethink"] = rethinkManager }
func (talk *Talk) UpdateLastMessageDate(userID, lastMessage string) error { talk.LastMessageDate = time.Now() talk.LastMessageUserId = userID talk.LastMessage = lastMessage talk.MsgNb += 1 _, err := r.Table("talks").Get(talk.Id).Update(talk).RunWrite(api.Sess) return err }
func (m DefaultManager) CreateConsoleSession(c *shipyard.ConsoleSession) error { if _, err := r.Table(tblNameConsole).Insert(c).RunWrite(m.session); err != nil { return err } m.logEvent("create-console-session", fmt.Sprintf("container=%s", c.ContainerID), []string{"console"}) return nil }
func (m DefaultManager) RemoveServiceKey(key string) error { if _, err := r.Table(tblNameServiceKeys).Filter(map[string]string{"key": key}).Delete().RunWrite(m.session); err != nil { return err } m.logEvent("delete-service-key", fmt.Sprintf("key=%s", key), []string{"security"}) return nil }
func (m DefaultManager) SaveServiceKey(key *auth.ServiceKey) error { if _, err := r.Table(tblNameServiceKeys).Insert(key).RunWrite(m.session); err != nil { return err } m.logEvent("add-service-key", fmt.Sprintf("description=%s", key.Description), []string{"security"}) return nil }
func (todo *Todo) clearTodosTable(request *restful.Request, response *restful.Response) { //On clear la table donc on supprime tout dans la table Todos _, err := r.Table("Todos").Delete().Run(session) if err != nil { response.WriteHeaderAndEntity(http.StatusInternalServerError, err.Error()) return } response.WriteHeader(http.StatusOK) }