Beispiel #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)
		}
	})
}
Beispiel #2
0
//Adds a new account to the db. Passwords are generated using bcrypt
func newAccountHandler(req *http.Request, db *gorm.DB, rendr render.Render) {
	username := req.FormValue("username")
	password := req.FormValue("password")

	if username == "" {
		log.Println(http.StatusBadRequest, "Username blank")
		rendr.Text(http.StatusBadRequest, "Supply valid username")
		return
	}
	if password == "" {
		log.Println(http.StatusBadRequest, "Password blank")
		rendr.Text(http.StatusBadRequest, "Supply valid password")
		return
	}

	hash, err := bcrypt.GenerateFromPassword([]byte(password), 0)
	if err != nil {
		log.Println(err.Error())
		rendr.Text(http.StatusBadRequest, err.Error())
		return
	}

	acc := &account{Username: username, Password: hash, Funds: 0}
	err = db.Create(acc).Error
	if err != nil {
		log.Println(err.Error())
		rendr.Text(http.StatusBadRequest, err.Error())
		return
	}
	rendr.Text(http.StatusOK, "Account created")
}
func PostProfileFieldCategory(db gorm.DB, router *gin.Engine) {
	// POST /profile_field_category
	// POST new profile_field_category to database
	router.POST("/profile_field_category", func(c *gin.Context) {
		var profile_field_categoryData model.ProfileFieldCategoryData
		if err := c.BindJSON(&profile_field_categoryData); err == nil {
			profile_field_category := &model.ProfileFieldCategory{
				ProfileFieldCategoryData: profile_field_categoryData,
			}

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

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
func PostSpaceSetting(db gorm.DB, router *gin.Engine) {
	// POST /space_setting
	// POST new space_setting to database
	router.POST("/space_setting", func(c *gin.Context) {
		var space_settingData model.SpaceSettingData
		if err := c.BindJSON(&space_settingData); err == nil {
			space_setting := &model.SpaceSetting{
				SpaceSettingData: space_settingData,
			}

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

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Beispiel #5
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)
		}
	})
}
Beispiel #6
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)
		}
	})
}
func PostUserPassword(db gorm.DB, router *gin.Engine) {
	// POST /user_password
	// POST new user_password to database
	router.POST("/user_password", func(c *gin.Context) {
		var user_passwordData model.UserPasswordData
		if err := c.BindJSON(&user_passwordData); err == nil {
			user_password := &model.UserPassword{
				UserPasswordData: user_passwordData,
			}

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

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Beispiel #8
0
func PostPost(db gorm.DB, router *gin.Engine) {
	// POST /post
	// POST new post to database
	router.POST("/post", func(c *gin.Context) {
		var postData model.PostData
		if err := c.BindJSON(&postData); err == nil {
			post := &model.Post{
				PostData: postData,
			}

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

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Beispiel #9
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)
		}
	})
}
Beispiel #10
0
func AddLinkHandler(cfg Config, w http.ResponseWriter, r *http.Request, db *gorm.DB, cachechan chan string) bool {

	/* Parse the form and check the URL arguments */
	r.ParseForm()

	title := r.FormValue("title")
	url := r.FormValue("url")
	description := r.FormValue("description")
	password := r.FormValue("password")

	if len(title) == 0 || len(url) == 0 || len(description) == 0 || len(password) == 0 {
		/* Return an error page if we're missing a field */
		return false
	}

	if password != cfg.Post.Password {
		/* Bad password, so we should show an error page */
		return false
	}

	link := Link{Title: title, URL: url, Description: description, Active: true}
	db.Create(&link)

	/* Let's queue the link for caching */
	cachechan <- url

	return true
}
Beispiel #11
0
func PostNotification(db gorm.DB, router *gin.Engine) {
	// POST /notification
	// POST new notification to database
	router.POST("/notification", func(c *gin.Context) {
		var notificationData model.NotificationData
		if err := c.BindJSON(&notificationData); err == nil {
			notification := &model.Notification{
				NotificationData: notificationData,
			}

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

		} else {
			log.Print(err)
			c.AbortWithError(http.StatusBadRequest, err)
		}
	})
}
Beispiel #12
0
func (s *Service) createUserCommon(db *gorm.DB, username, password string) (*User, error) {
	// Start with a user without a password
	user := &User{
		Username: username,
		Password: util.StringOrNull(""),
	}

	// If the password is being set already, create a bcrypt hash
	if password != "" {
		passwordHash, err := pass.HashPassword(password)
		if err != nil {
			return nil, err
		}
		user.Password = util.StringOrNull(string(passwordHash))
	}

	// Check the username is available
	if s.UserExists(user.Username) {
		return nil, ErrUsernameTaken
	}

	// Create the user
	if err := db.Create(user).Error; err != nil {
		return nil, err
	}
	return user, nil
}
Beispiel #13
0
Datei: dao.go Projekt: itpkg/base
func (p *SettingDao) Set(db *gorm.DB, key string, val interface{}, enc bool) error {
	dt, err := web.ToBits(val)
	if err != nil {
		db.Rollback()
		return err
	}

	if enc {
		dt, err = p.Aes.Encode(dt)
		if err != nil {
			db.Rollback()
			return err
		}
	}

	st := Setting{ID: key}
	var cn int
	db.Model(st).Count(&cn)
	if cn == 0 {
		st.Val = dt
		db.Create(&st)
	} else {
		db.Model(&st).Updates(Setting{Val: dt})
	}
	return nil
}
Beispiel #14
0
// NewSpendingType Function
func NewSpendingType(f forms.AddSpendingTypeForm, DB *gorm.DB) (spendingType SpendingType, err []helper.ErrorMessage) {

	v := f.Validate()

	if v.HasErrors() {
		for _, value := range v.Errors {
			err = append(err, helper.ErrorMessage{
				Code:    409,
				Source:  helper.SourceErrors{Pointer: value.Key},
				Title:   value.Message,
				Details: value.Message,
			})
		}

		return spendingType, err
	}

	spendingType.Name = f.Data.Name
	spendingType.Description = f.Data.Description

	_err := DB.Create(&spendingType).Error
	if _err != nil {
		err = append(err, helper.ErrorMessage{
			Code:    409,
			Source:  helper.SourceErrors{},
			Title:   "Failed Creating New Spending Type",
			Details: _err.Error(),
		})

		return spendingType, err
	}

	return spendingType, nil
}
Beispiel #15
0
// Bootstrap creates "migrations" table
// to keep track of already run database migrations
func Bootstrap(db *gorm.DB) error {
	migrationName := "bootstrap_migrations"

	migration := new(Migration)
	// Using Error instead of RecordNotFound because we want to check
	// if the migrations table exists. This is different from later migrations
	// where we query the already create migrations table.
	exists := nil == db.Where("name = ?", migrationName).First(migration).Error

	if exists {
		logger.Infof("Skipping %s migration", migrationName)
		return nil
	}

	logger.Infof("Running %s migration", migrationName)

	// Create migrations table
	if err := db.CreateTable(new(Migration)).Error; err != nil {
		return fmt.Errorf("Error creating migrations table: %s", db.Error)
	}

	// Save a record to migrations table,
	// so we don't rerun this migration again
	migration.Name = migrationName
	if err := db.Create(migration).Error; err != nil {
		return fmt.Errorf("Error saving record to migrations table: %s", err)
	}

	return nil
}
Beispiel #16
0
func (s *Service) createUserCommon(db *gorm.DB, roleID, username, password string) (*models.OauthUser, error) {
	// Start with a user without a password
	user := &models.OauthUser{
		RoleID:   util.StringOrNull(roleID),
		Username: strings.ToLower(username),
		Password: util.StringOrNull(""),
	}

	// If the password is being set already, create a bcrypt hash
	if password != "" {
		if len(password) < MinPasswordLength {
			return nil, ErrPasswordTooShort
		}
		passwordHash, err := pass.HashPassword(password)
		if err != nil {
			return nil, err
		}
		user.Password = util.StringOrNull(string(passwordHash))
	}

	// Check the username is available
	if s.UserExists(user.Username) {
		return nil, ErrUsernameTaken
	}

	// Create the user
	if err := db.Create(user).Error; err != nil {
		return nil, err
	}
	return user, nil
}
Beispiel #17
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
}
Beispiel #18
0
func insertValues(db *gorm.DB, record []string) {
	// Append quotations for the STRING types
	for i := 0; i <= 7; i++ {
		record[i] = record[i][1:len(record[i])]
	}

	// Convert string records into integers
	start_t, startErr := strconv.Atoi(record[0])
	check("strconv start error", startErr)
	stop_t, stopErr := strconv.Atoi(record[1])
	check("strconv stop error", stopErr)
	count, countErr := strconv.Atoi(record[7])
	check("strconv count error", countErr)

	minecraft := Record{
		Start_t:   start_t,
		Stop_t:    stop_t,
		Server_id: record[2],
		Player_a:  record[3],
		Player_b:  record[4],
		Key:       record[5],
		Meta:      record[6],
		Count:     count,
	}

	db.Create(minecraft)
}
Beispiel #19
0
func NewEntityEvent(id int, typ, data string, intdata int, db gorm.DB) (ret EntityEvent, err error) {
	ret.Data = data
	ret.Type = typ
	ret.IntData = intdata
	ret.EntityID = id
	err = db.Create(&ret).Error
	return
}
Beispiel #20
0
func (db *SQLStorage) writeChangefeed(tx *gorm.DB, gun string, version int, checksum string) error {
	c := &Change{
		GUN:      gun,
		Version:  version,
		SHA256:   checksum,
		Category: changeCategoryUpdate,
	}
	return tx.Create(c).Error
}
Beispiel #21
0
func ormTest(db gorm.DB) []model.User {
	user := model.User{Name: "Jinzhu", Age: 18, Birthday: time.Now()}
	db.NewRecord(user) // => returns `true` if primary key is blank
	db.Create(&user)
	db.NewRecord(user) // => return `false` after `user` created
	users := []model.User{}
	db.First(&users)
	return users
}
Beispiel #22
0
func Create(u *UserJSON, DB *gorm.DB) *gorm.DB {
	user := User{
		FirstName: u.FirstName,
		LastName:  u.LastName,
		Email:     u.Email,
		Account:   account.Account{Password: utils.CryptPass(u.Password)},
	}

	return DB.Create(&user).Find(&user)
}
Beispiel #23
0
//Called when a user logged in to create a new session
//pass the UserID (PK in the DB) and a string describing what
//they are logging in to (ie: web, IRC etc)
func CreateSession(userID int, component string, db gorm.DB) string {
	s := Session{
		Key:       util.RandAlphaKey(DEFAULT_KEY_SIZE),
		UserID:    userID,
		Component: component,
		Expires:   time.Now().Add(DEFAULT_EXPIRY),
		Revoked:   false,
	}
	db.Create(&s)
	return s.Key
}
Beispiel #24
0
// SaveMigration saves a migration to the migration table
func SaveMigration(db *gorm.DB, migrationName string) error {
	migration := new(Migration)
	migration.Name = migrationName

	if err := db.Create(migration).Error; err != nil {
		logger.Errorf("Error saving record to migrations table: %s", err)
		return fmt.Errorf("Error saving record to migrations table: %s", err)
	}

	return nil
}
// CreateSummary inserts a Summary into the database
func CreateSummary(db *gorm.DB, sum Summary) (bool, Summary) {

	created := db.NewRecord(sum) // => returns `true` as primary key is blank

	if !created {
		return false, sum
	}

	db.Create(&sum)

	return true, sum
}
Beispiel #26
0
Datei: dao.go Projekt: itpkg/base
func (p *AuthDao) CreateByEmail(db *gorm.DB, email, name, password string) *User {
	u := User{
		Provider: "email",
		Name:     name,
		Email:    email,
		Password: p.HMac.Sum([]byte(password)),
		Token:    email,
		Contact:  Contact{},
	}
	db.Create(&u)
	return &u
}
Beispiel #27
0
func addUser(db *gorm.DB, name string, pass string) error {
	user := new(User)
	user.Name = name
	user.Password = passHash(pass)

	// ok := db.NewRecord(user)
	// log.Printf("New user %s %v\n", name, ok)
	if err := db.Create(&user).Error; err != nil {
		log.Print(err)
		return err
	}
	return nil
}
// Save tweet to database
func (tweet *Tweet) Save(db *gorm.DB) (err error) {
	err = db.Create(tweet).Error
	if err != nil {
		return
	}
	for i := range tweet.Replies {
		err = db.Create(&tweet.Replies[i]).Error
		if err != nil {
			return
		}
	}
	return
}
// GetCreateTaskHandler creates HTTP handler for Create Task operation
func GetCreateTaskHandler(db *gorm.DB) echo.HandlerFunc {
	return func(c *echo.Context) error {
		task := model.Task{}
		if err := c.Bind(&task); err != nil {
			return err
		}

		if err := db.Create(&task).Error; err != nil {
			return c.JSON(http.StatusInternalServerError, NewApiError(err.Error()))
		}

		return c.JSON(http.StatusCreated, task)
	}
}
Beispiel #30
-1
Datei: dao.go Projekt: itpkg/base
func (p *LocaleDao) Set(db *gorm.DB, lang, code, message string) {
	var l Locale
	if db.Select("id").Where("lang = ? AND code = ?", lang, code).First(&l).RecordNotFound() {
		db.Create(&Locale{Lang: lang, Code: code, Message: message})
	} else {
		db.Model(Locale{}).Where("id = ?", l.ID).Updates(Locale{Message: message})
	}
}