Exemplo n.º 1
3
func PostLike(db gorm.DB, router *gin.Engine) {
	// POST /like
	// POST new like to database
	router.POST("/like", func(c *gin.Context) {
		var likeData model.LikeData
		if err := c.BindJSON(&likeData); err == nil {
			like := &model.Like{
				LikeData: likeData,
			}

			var x_user uint64
			if resp := c.Request.Header.Get(userHeader); resp != "" {
				conv_user, _ := strconv.ParseUint(resp, 10, 64)
				x_user = conv_user
				like.Trace.CreatedBy = x_user
				like.Trace.UpdatedBy = x_user
				if err := checkDataLike(like.LikeData); err {
					if err := db.Create(&like).Error; err != nil {
						c.AbortWithError(http.StatusBadRequest, err)
					} else {
						c.JSON(http.StatusCreated, like)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			} else {
				c.AbortWithStatus(http.StatusForbidden)
			}

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 2
0
func PostActivity(db gorm.DB, router *gin.Engine) {
	// POST /activity
	// POST new activity to database
	router.POST("/activity", func(c *gin.Context) {
		var activityData model.ActivityData
		if err := c.BindJSON(&activityData); err == nil {
			activity := &model.Activity{
				ActivityData: activityData,
			}

			var x_user uint64
			if resp := c.Request.Header.Get(userHeader); resp != "" {
				conv_user, _ := strconv.ParseUint(resp, 10, 64)
				x_user = conv_user
				activity.Trace.CreatedBy = x_user
				activity.Trace.UpdatedBy = x_user
				if err := checkDataActivity(activity.ActivityData); err {
					if err := db.Create(&activity).Error; err != nil {
						c.AbortWithError(http.StatusBadRequest, err)
					} else {
						c.JSON(http.StatusCreated, activity)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			} else {
				c.AbortWithStatus(http.StatusForbidden)
			}

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 3
0
// releasesCreate creates a new Release and inserts it into the database.
func releasesCreate(db *gorm.DB, release *Release) (*Release, error) {
	t := db.Begin()

	// Get the last release version for this app.
	v, err := releasesLastVersion(t, release.App.ID)
	if err != nil {
		t.Rollback()
		return release, err
	}

	// Increment the release version.
	release.Version = v + 1

	if err := t.Create(release).Error; err != nil {
		t.Rollback()
		return release, err
	}

	if err := t.Commit().Error; err != nil {
		t.Rollback()
		return release, err
	}

	return release, nil
}
Exemplo n.º 4
0
// addSkip adds skip parameter into sql query
func addSkip(query *gorm.DB, skip int) *gorm.DB {
	if skip > 0 {
		return query.Offset(skip)
	}

	return query
}
Exemplo n.º 5
0
func isAuthorized(db *gorm.DB, nameOfTable, header string) (*authPair, bool) {
	// blank login and password with ":" separator return, in base64, a size of 10 char
	if len(header) <= 10 {
		return nil, false
	}

	var i int
	var u authPair
	var cred string

	// get credentials from header
	if value, err := base64.StdEncoding.DecodeString(header[6:]); err != nil {
		return nil, false
	} else {
		cred = string(value)
	}

	// check ":" separator
	i = strings.Index(cred, ":")

	// check present in database
	db.Table(nameOfTable).Select(
		"identifiant, mot_de_passe").Where(
		"identifiant=? and mot_de_passe=?", cred[:i], cred[i+1:]).Find(&u)

	if reflect.DeepEqual(u, authPair{}) {
		return nil, false
	}

	// success
	return &u, true
}
Exemplo n.º 6
0
func MediaCreate(db gorm.DB, r render.Render, media models.Media) {
	if err := db.Save(&media).Error; err != nil {
		r.JSON(http.StatusConflict, map[string]interface{}{"error": "Media conflict"})
		return
	}
	r.JSON(http.StatusCreated, media)
}
Exemplo n.º 7
0
func AddUserFile(db *gorm.DB, udt *UserFileInfo, content []byte) error {

	lastId, err := getLastFileIdByUserId(db, udt.UserId)
	if err != nil {
		revel.TRACE.Println(err)
		return err
	}
	nextId := lastId + 1
	// revel.INFO.Println("Next DS id: ", nextId)
	udt.FileId = nextId

	err = db.Save(udt).Error
	if err != nil {
		revel.TRACE.Println(err)
		return err
	}

	ds := &UserFile{
		UserId:  udt.UserId,
		FileId:  udt.FileId,
		Content: content,
	}

	err = db.Save(ds).Error
	if err != nil {
		revel.TRACE.Println(err)
		return err
	}

	return err
}
Exemplo n.º 8
0
func AddTables(db *gorm.DB) error {
	err := db.AutoMigrate(UserFileInfo{}).Error
	if err != nil {
		return err
	}
	return db.AutoMigrate(UserFile{}).Error
}
Exemplo n.º 9
0
func PutGroupAdmin(db gorm.DB, router *gin.Engine) {
	// PUT /group_admin
	// Update group_admin data by id
	router.PUT("/group_admin/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var group_adminData model.GroupAdminData
			if err := c.BindJSON(&group_adminData); err == nil {
				group_admin := &model.GroupAdmin{
					GroupAdminData: group_adminData,
					GroupAdminId:   model.GroupAdminId{Id: id},
				}
				if err := checkDataGroupAdmin(group_admin.GroupAdminData); err {
					checkGroupAdmin := &model.GroupAdmin{
						GroupAdminData: group_adminData,
						GroupAdminId:   model.GroupAdminId{Id: id},
					}
					if err := db.First(checkGroupAdmin).Error; err == nil {
						db.Save(&group_admin)
						c.JSON(http.StatusOK, group_admin)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 10
0
func PostGroupAdmin(db gorm.DB, router *gin.Engine) {
	// POST /group_admin
	// POST new group_admin to database
	router.POST("/group_admin", func(c *gin.Context) {
		var group_adminData model.GroupAdminData
		if err := c.BindJSON(&group_adminData); err == nil {
			group_admin := &model.GroupAdmin{
				GroupAdminData: group_adminData,
			}

			var x_user uint64
			if resp := c.Request.Header.Get(userHeader); resp != "" {
				conv_user, _ := strconv.ParseUint(resp, 10, 64)
				x_user = conv_user
				group_admin.Trace.CreatedBy = x_user
				group_admin.Trace.UpdatedBy = x_user
				if err := checkDataGroupAdmin(group_admin.GroupAdminData); err {
					if err := db.Create(&group_admin).Error; err != nil {
						c.AbortWithError(http.StatusBadRequest, err)
					} else {
						c.JSON(http.StatusCreated, group_admin)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			} else {
				c.AbortWithStatus(http.StatusForbidden)
			}

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 11
0
func AllDistinctDates(db gorm.DB) []Date {
	var results []Date
	scope := db.Table("media").Select("date_part('day', taken_at) as day, date_part('month', taken_at) as month, date_part('year', taken_at) as year")
	scope = scope.Group("day, month, year").Order("year, month, day")
	scope.Scan(&results)
	return results
}
Exemplo n.º 12
0
func compositeIndex(table *gorm.DB, kind string, primary_key string, dst interface{}, parents []string) {

	index_name := "idx_" + kind + "_" + primary_key
	indexes := []string{primary_key}

	if len(parents) == 0 {
		parents = []string{}
		st := reflect.TypeOf(dst).Elem()
		for i := 0; i < st.NumField(); i++ {
			field := st.Field(i)
			pacific_parent := field.Tag.Get("pacific_parent")
			if pacific_parent != "" {
				parents = append(parents, pacific_parent)
			}
		}
	}

	for _, parent := range parents {
		if parent != "" {
			index_name = index_name + "_" + parent
			indexes = append(indexes, parent)
		}
	}

	if len(indexes) > 0 {
		table.AddUniqueIndex(index_name, indexes...) //TODO: if not exists?
	}
}
Exemplo n.º 13
0
func isAuthorized(db *gorm.DB, nameOfTable, header string) (*authPair, bool) {

	var i int
	var u authPair
	var cred string

	// get credentials from header
	if value, err := base64.StdEncoding.DecodeString(header); err != nil {
		return nil, false
	} else {
		cred = string(value)
	}

	// check format
	if i = strings.Index(cred, ":"); len(cred) < 8 || i < 8 {
		return nil, false
	}

	// check present in database
	db.Table(nameOfTable).Select(
		"identifiant, mot_de_passe").Where(
		"identifiant=? and mot_de_passe=?", cred[6:i], cred[i:]).Find(&u)
	if reflect.DeepEqual(u, authPair{}) {
		return nil, false
	}

	// success
	return &u, true
}
Exemplo n.º 14
0
func storeFact(Fact *models.Fact, db *gorm.DB) (*models.Fact, error) {
	var err error

	if Fact == nil {
		return nil, errors.New("save: fact is nil")
	}

	if Fact.ID == 0 {
		err := db.Create(Fact).Error
		if err != nil {
			return nil, err
		}
	}

	var f models.Fact

	if err := db.Where(&models.Fact{ID: Fact.ID}).First(&f).Error; err != nil {
		return nil, err
	}
	if err := db.Where(f.ActionID).First(&f.Action).Error; err != nil {
		return nil, err
	}
	err = db.Where(f.ContactID).First(&f.Contact).Error
	if err != nil { //&& err != gorm.RecordNotFound
		return nil, err
	}

	if err == nil {
		if err := db.Where(f.Contact.AddressID).First(&f.Contact.Address).Error; err != nil { //&& err != gorm.RecordNotFound
			return nil, err
		}
	}

	return &f, nil
}
Exemplo n.º 15
0
func PutActivity(db gorm.DB, router *gin.Engine) {
	// PUT /activity
	// Update activity data by id
	router.PUT("/activity/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var activityData model.ActivityData
			if err := c.BindJSON(&activityData); err == nil {
				activity := &model.Activity{
					ActivityData: activityData,
					ActivityId:   model.ActivityId{Id: id},
				}
				if err := checkDataActivity(activity.ActivityData); err {
					checkActivity := &model.Activity{
						ActivityData: activityData,
						ActivityId:   model.ActivityId{Id: id},
					}
					if err := db.First(checkActivity).Error; err == nil {
						db.Save(&activity)
						c.JSON(http.StatusOK, activity)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 16
0
func getPlayerWeapons(db *gorm.DB, player uint) []WeaponStat {

	// have some initial capacity
	ws := make([]WeaponStat, 0, 10)

	rows, err := db.Table("weapon_stats").
		Select("type, sum(weapon_stats.shots) as shots, sum(weapon_stats.hits) as hits, sum(weapon_stats.kills) as kills").
		Joins("join player_match_stats on weapon_stats.player_match_stat_id = player_match_stats.id").
		Joins("join aliases on player_match_stats.alias_id = aliases.id").
		Where("aliases.player_id = ?", player).
		Group("weapon_stats.type").
		Rows()

	if err != nil {
		log.Printf("query failed: %s", err)
		return ws
	}

	for rows.Next() {
		var t string     // type
		var k, s, h uint // kills, shots, hits
		if err := rows.Scan(&t, &s, &h, &k); err != nil {
			log.Printf("failed to scan row: %s", err)
		}
		log.Printf("stats: %s %v %v %v", t, s, h, k)
		ws = append(ws, WeaponStat{
			Shots: s,
			Kills: k,
			Hits:  h,
			Type:  t,
		})
	}

	return ws
}
Exemplo n.º 17
0
func PutLike(db gorm.DB, router *gin.Engine) {
	// PUT /like
	// Update like data by id
	router.PUT("/like/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var likeData model.LikeData
			if err := c.BindJSON(&likeData); err == nil {
				like := &model.Like{
					LikeData: likeData,
					LikeId:   model.LikeId{Id: id},
				}
				if err := checkDataLike(like.LikeData); err {
					checkLike := &model.Like{
						LikeData: likeData,
						LikeId:   model.LikeId{Id: id},
					}
					if err := db.First(checkLike).Error; err == nil {
						db.Save(&like)
						c.JSON(http.StatusOK, like)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 18
0
func PostWallEntry(db gorm.DB, router *gin.Engine) {
	// POST /wall_entry
	// POST new wall_entry to database
	router.POST("/wall_entry", func(c *gin.Context) {
		var wall_entryData model.WallEntryData
		if err := c.BindJSON(&wall_entryData); err == nil {
			wall_entry := &model.WallEntry{
				WallEntryData: wall_entryData,
			}

			var x_user uint64
			if resp := c.Request.Header.Get(userHeader); resp != "" {
				conv_user, _ := strconv.ParseUint(resp, 10, 64)
				x_user = conv_user
				wall_entry.Trace.CreatedBy = x_user
				wall_entry.Trace.UpdatedBy = x_user
				if err := checkDataWallEntry(wall_entry.WallEntryData); err {
					if err := db.Create(&wall_entry).Error; err != nil {
						c.AbortWithError(http.StatusBadRequest, err)
					} else {
						c.JSON(http.StatusCreated, wall_entry)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			} else {
				c.AbortWithStatus(http.StatusForbidden)
			}

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 19
0
func DropTables(db *gorm.DB) error {
	err := db.DropTable(UserFileInfo{}).Error
	if err != nil {
		return err
	}
	return db.DropTable(UserFile{}).Error
}
Exemplo n.º 20
0
func PutWallEntry(db gorm.DB, router *gin.Engine) {
	// PUT /wall_entry
	// Update wall_entry data by id
	router.PUT("/wall_entry/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var wall_entryData model.WallEntryData
			if err := c.BindJSON(&wall_entryData); err == nil {
				wall_entry := &model.WallEntry{
					WallEntryData: wall_entryData,
					WallEntryId:   model.WallEntryId{Id: id},
				}
				if err := checkDataWallEntry(wall_entry.WallEntryData); err {
					checkWallEntry := &model.WallEntry{
						WallEntryData: wall_entryData,
						WallEntryId:   model.WallEntryId{Id: id},
					}
					if err := db.First(checkWallEntry).Error; err == nil {
						db.Save(&wall_entry)
						c.JSON(http.StatusOK, wall_entry)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 21
0
Arquivo: blog.go Projeto: bishen/blog
func ClassifyPost(params martini.Params, res http.ResponseWriter, cls models.Classify, db *gorm.DB) string {
	db.Save(&cls)
	fi, err := os.Open("./jade/layout-tmpl.jade")
	if err != nil {
		panic(err)
	}
	defer fi.Close()
	fd, err2 := ioutil.ReadAll(fi)

	f, err2 := os.OpenFile("./jade/layout.jade", os.O_RDWR, 0755)
	if err2 != nil {
		panic(err)
	}

	css := []models.Classify{}
	db.Find(&css)
	var buf bytes.Buffer
	for _, v := range css {
		buf.WriteString("        a(href=\"/" + v.Url + ".html\") " + v.Title + "\n")
	}
	w := strings.Replace(string(fd), "####", buf.String(), -1)
	n, err1 := io.WriteString(f, w) //写入文件(字符串)
	if err1 != nil {
		panic(err1)
	}
	fmt.Printf("写入 %d 个字节n", n)
	return "1"
}
Exemplo n.º 22
0
func PutFile(db gorm.DB, router *gin.Engine) {
	// PUT /file
	// Update file data by id
	router.PUT("/file/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var fileData model.FileData
			if err := c.BindJSON(&fileData); err == nil {
				file := &model.File{
					FileData: fileData,
					FileId:   model.FileId{Id: id},
				}
				if err := checkDataFile(file.FileData); err {
					checkFile := &model.File{
						FileData: fileData,
						FileId:   model.FileId{Id: id},
					}
					if err := db.First(checkFile).Error; err == nil {
						db.Save(&file)
						c.JSON(http.StatusOK, file)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 23
0
// BeforeSave invokes required actions before persisting.
func (u *Team) BeforeSave(db *gorm.DB) (err error) {
	if u.Slug == "" {
		for i := 0; true; i++ {
			if i == 0 {
				u.Slug = slugify.Slugify(u.Name)
			} else {
				u.Slug = slugify.Slugify(
					fmt.Sprintf("%s-%d", u.Name, i),
				)
			}

			notFound := db.Where(
				"slug = ?",
				u.Slug,
			).Not(
				"id",
				u.ID,
			).First(
				&Team{},
			).RecordNotFound()

			if notFound {
				break
			}
		}
	}

	return nil
}
Exemplo n.º 24
0
func GroupCreate(db gorm.DB, r render.Render, group models.Group) {
	if err := db.Save(&group).Error; err != nil {
		r.JSON(http.StatusConflict, map[string]interface{}{"error": "Group conflict"})
		return
	}
	r.JSON(http.StatusCreated, group)
}
Exemplo n.º 25
0
// addPluck basically adds select statement for
// only required fields
func addPluck(query *gorm.DB, plucked string) *gorm.DB {
	if plucked == "" {
		return query
	}

	return query.Select(plucked)
}
Exemplo n.º 26
0
// BeforeSave invokes required actions before persisting.
func (u *User) BeforeSave(db *gorm.DB) (err error) {
	if u.Slug == "" {
		for i := 0; true; i++ {
			if i == 0 {
				u.Slug = slugify.Slugify(u.Username)
			} else {
				u.Slug = slugify.Slugify(
					fmt.Sprintf("%s-%d", u.Username, i),
				)
			}

			notFound := db.Where(
				"slug = ?",
				u.Slug,
			).Not(
				"id",
				u.ID,
			).First(
				&User{},
			).RecordNotFound()

			if notFound {
				break
			}
		}
	}

	if u.Email != "" {
		email, err := govalidator.NormalizeEmail(
			u.Email,
		)

		if err != nil {
			return fmt.Errorf("Failed to normalize email")
		}

		u.Email = email
	}

	if u.Password != "" {
		encrypt, err := bcrypt.GenerateFromPassword(
			[]byte(u.Password),
			bcrypt.DefaultCost,
		)

		if err != nil {
			return fmt.Errorf("Failed to encrypt password")
		}

		u.Hashword = string(encrypt)
	}

	if u.Hash == "" {
		u.Hash = base32.StdEncoding.EncodeToString(
			securecookie.GenerateRandomKey(32),
		)
	}

	return nil
}
Exemplo n.º 27
0
func PutUserHttpSession(db gorm.DB, router *gin.Engine) {
	// PUT /user_http_session
	// Update user_http_session data by id
	router.PUT("/user_http_session/:id", func(c *gin.Context) {
		_id := c.Param("id")
		if id, err := strconv.ParseUint(_id, 10, 64); err == nil {
			var user_http_sessionData model.UserHttpSessionData
			if err := c.BindJSON(&user_http_sessionData); err == nil {
				user_http_session := &model.UserHttpSession{
					UserHttpSessionData: user_http_sessionData,
					UserHttpSessionId:   model.UserHttpSessionId{Id: id},
				}
				if err := checkDataUserHttpSession(user_http_session.UserHttpSessionData); err {
					checkUserHttpSession := &model.UserHttpSession{
						UserHttpSessionData: user_http_sessionData,
						UserHttpSessionId:   model.UserHttpSessionId{Id: id},
					}
					if err := db.First(checkUserHttpSession).Error; err == nil {
						db.Save(&user_http_session)
						c.JSON(http.StatusOK, user_http_session)
					} else {
						c.AbortWithStatus(http.StatusNotFound)
					}
				} else {
					c.AbortWithStatus(http.StatusBadRequest)
				}
			}
		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Exemplo n.º 28
0
func initDb() (l *Logger) {
	exists := false
	var err error
	var db *gorm.DB

	if _, err := os.Stat(dbfile); err == nil {
		log.Println("Database file already exists.")
		exists = true
	}

	db, err = gorm.Open("sqlite3", dbfile)
	if err != nil {
		log.Printf("Unable to open database file: %s\n", err)
		return nil
	}

	if !exists {
		db.CreateTable(&LogMessage{})
	}

	l = &Logger{
		db:     db,
		dbPath: dbfile,
	}

	return l
}
Exemplo n.º 29
0
func FacultiesDepartments(db *gorm.DB) ([]json_models.FacultiesDepartments, error) {
	var result []json_models.FacultiesDepartments

	err := db.Model(&models.Faculties{}).Select("id as faculty_id, short_name as faculty_name").Scan(&result).Error

	if err != nil {
		return nil, err
	}

	for i, faculty := range result {
		var records []models.Departments
		err := db.Preload("Faculty").Where("faculty_id = ?", faculty.FacultyId).Find(&records).Error
		if err != nil {
			return nil, err
		}

		if len(records) != 0 {
			for _, record := range records {
				val := json_models.Department{Id: record.Id, Name: record.Name}
				result[i].Departments = append(result[i].Departments, val)
			}
		} else {
			result[i].Departments = []json_models.Department{}
		}
	}

	return result, nil
}
Exemplo n.º 30
0
// GetRepo retrieves a specific repo from the database.
func (db *data) GetRepo(id string) (*model.Repo, *gorm.DB) {
	var (
		record = &model.Repo{}
		query  *gorm.DB
	)

	if match, _ := regexp.MatchString("^([0-9]+)$", id); match {
		val, _ := strconv.ParseInt(id, 10, 64)

		query = db.Where(
			"id = ?",
			val,
		)
	} else {
		query = db.Where(
			"slug = ?",
			id,
		)
	}

	res := query.Model(
		&record,
	).Preload(
		"Org",
	).Preload(
		"Org.Registry",
	).Preload(
		"Tags",
	).First(
		&record,
	)

	return record, res
}