Skip to content
Permalink
Browse files

05-Database init data

  • Loading branch information...
bonfy committed Sep 11, 2018
1 parent 2306009 commit 834242739814757253916f6e2e6ef439dce96c0d
Showing with 65 additions and 0 deletions.
  1. +23 −0 cmd/db_init/main.go
  2. +9 −0 model/post.go
  3. +19 −0 model/user.go
  4. +14 −0 model/utils.go
@@ -15,4 +15,27 @@ func main() {

db.DropTableIfExists(model.User{}, model.Post{})
db.CreateTable(model.User{}, model.Post{})

users := []model.User{
{
Username: "bonfy",
PasswordHash: model.GeneratePasswordHash("abc123"),
Posts: []model.Post{
{Body: "Beautiful day in Portland!"},
},
},
{
Username: "rene",
PasswordHash: model.GeneratePasswordHash("abc123"),
Email: "rene@test.com",
Posts: []model.Post{
{Body: "The Avengers movie was so cool!"},
{Body: "Sun shine is beautiful"},
},
},
}

for _, u := range users {
db.Debug().Create(&u)
}
}
@@ -12,3 +12,12 @@ type Post struct {
Body string `gorm:"varchar(180)"`
Timestamp *time.Time `sql:"DEFAULT:current_timestamp"`
}

// GetPostsByUserID func
func GetPostsByUserID(id int) (*[]Post, error) {
var posts []Post
if err := db.Preload("User").Where("user_id=?", id).Find(&posts).Error; err != nil {
return nil, err
}
return &posts, nil
}
@@ -9,3 +9,22 @@ type User struct {
Posts []Post
Followers []*User `gorm:"many2many:follower;association_jointable_foreignkey:follower_id"`
}

// SetPassword func: Set PasswordHash
func (u *User) SetPassword(password string) {
u.PasswordHash = GeneratePasswordHash(password)
}

// CheckPassword func
func (u *User) CheckPassword(password string) bool {
return GeneratePasswordHash(password) == u.PasswordHash
}

// GetUserByUsername func
func GetUserByUsername(username string) (*User, error) {
var user User
if err := db.Where("username=?", username).Find(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
@@ -0,0 +1,14 @@
package model

import (
"crypto/md5"
"encoding/hex"
)

// GeneratePasswordHash : Use MD5
func GeneratePasswordHash(pwd string) string {
hasher := md5.New()
hasher.Write([]byte(pwd))
pwdHash := hex.EncodeToString(hasher.Sum(nil))
return pwdHash
}

0 comments on commit 8342427

Please sign in to comment.
You can’t perform that action at this time.