Skip to content

Commit

Permalink
05-Database init data
Browse files Browse the repository at this point in the history
  • Loading branch information
bonfy committed Sep 11, 2018
1 parent 2306009 commit 8342427
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 0 deletions.
23 changes: 23 additions & 0 deletions cmd/db_init/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
9 changes: 9 additions & 0 deletions model/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
19 changes: 19 additions & 0 deletions model/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
14 changes: 14 additions & 0 deletions model/utils.go
Original file line number Diff line number Diff line change
@@ -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.