Compare commits

...

No commits in common. 'news' and 'a905a4f0470799538ccc6bb4bdc66c21caaa1445' have entirely different histories.

  1. 5
      .env
  2. 111
      controllers/eventsController.go
  3. 112
      controllers/newsController.go
  4. 38
      controllers/postsController.go
  5. 20
      controllers/usersController.go
  6. BIN
      go-crud.exe
  7. BIN
      go-crud.exe~
  8. 30
      go.mod
  9. 41
      go.sum
  10. 13
      initializers/database.go
  11. 10
      initializers/loadEnvVariables.go
  12. 4
      initializers/syncDatabase.go
  13. 25
      main.go
  14. 21
      middleware/requireAuth.go
  15. 16
      migrate/migrate.go
  16. 16
      models/eventModel.go
  17. 13
      models/newsModels.go
  18. 4
      models/postModel.go
  19. 0
      models/userModel.go

5
.env

@ -1,2 +1,3 @@
DB_URL=postgres://dfbenvnp:SewGwQgomn3Aa-x60mdCfok37TPRGIio@topsy.db.elephantsql.com:5432/dfbenvnp PORT=8000
PORT=3000 SECRET=sdc87sdf6gv87df6v8sd7f6v8sdf76v8sdf7v6
DB_URL="host=dumbo.db.elephantsql.com user=yvvpeiee password=QwAhcTtiKL8j9qRyUBIqs9kNbu3O0_FB dbname=yvvpeiee port=5432 sslmode=disable"

111
controllers/eventsController.go

@ -0,0 +1,111 @@
package controllers
import (
"go-crud/initializers"
"go-crud/models"
"time"
"github.com/gin-gonic/gin"
)
func EventsCreate(c *gin.Context) {
// Get data off req body
var body struct {
Name string
Content string
PostBy string
Category string
}
c.Bind(&body)
// Create a event
now := time.Now()
event := models.Event{
Name: body.Name,
Content: body.Content,
PostBy: body.PostBy,
Category: body.Category,
Date: &now,
}
result := initializers.DB.Create(&event)
if result.Error != nil {
c.Status(400)
return
}
// Return it
c.JSON(200, gin.H{
"event": event,
})
}
func EventsIndex(c *gin.Context) {
// Get the events
var events []models.Event
initializers.DB.Find(&events)
// Respond with them
c.JSON(200, gin.H{
"event": events,
})
}
func EventsShow(c *gin.Context) {
// Get id off URL
id := c.Param("id")
// Get the events
var event models.Event
initializers.DB.First(&event, id)
// Respond with them
c.JSON(200, gin.H{
"event": event,
})
}
func EventsUpdate(c *gin.Context) {
// Get the id off the URL
id := c.Param("id")
// Get the data off req body
var body struct {
Name string
Content string
PostBy string
Category string
Date *time.Time
}
c.Bind(&body)
// Find the post were updating
var event models.Event
initializers.DB.First(&event, id)
// Update it
now := time.Now()
initializers.DB.Model(&event).Updates(models.Event{
Name: body.Name,
Content: body.Content,
PostBy: body.PostBy,
Category: body.Category,
Date: &now,
})
// Respond with it
c.JSON(200, gin.H{
"event": event,
})
}
func EventsDelete(c *gin.Context) {
// Get the id off the URL
id := c.Param("id")
// Delete the post
initializers.DB.Delete(&models.Event{}, id)
// Respond
c.Status(200)
}

112
controllers/newsController.go

@ -1,112 +0,0 @@
package controllers
import (
"go-crud/initializers"
"go-crud/models"
"time"
"github.com/gin-gonic/gin"
)
func NewsCreate(c *gin.Context) {
// Get data
var body struct {
Title string
Content string
Author string
CreatedBy string
}
c.Bind(&body)
// Create a news
now := time.Now()
news := models.News{
Title: body.Title,
Content: body.Content,
Author: body.Author,
CreatedBy: body.CreatedBy,
CreatedAt: now,
Date: now,
}
result := initializers.DB.Create(&news)
if result.Error != nil {
c.Status(400)
return
}
// Return
c.JSON(200, gin.H{
"news": news,
})
}
func NewsIndex(c *gin.Context) {
// Get news
var news []models.News
initializers.DB.Find(&news)
// Response
c.JSON(200, gin.H{
"news": news,
})
}
func NewsShow(c *gin.Context) {
// Get id
id := c.Param("id")
// Get the news
var news models.News
initializers.DB.First(&news, id)
// Response
c.JSON(200, gin.H{
"news": news,
})
}
func NewsUpdate(c *gin.Context) {
// Get id
id := c.Param("id")
// Get data
var body struct {
Title string
Content string
Author string
CreatedBy string
}
c.Bind(&body)
// find
var news models.News
initializers.DB.First(&news, id)
//Update
initializers.DB.Model(&news).Updates(models.News{
Title: body.Title,
Content: body.Content,
Author: body.Author,
CreatedBy: body.CreatedBy,
})
// Response
c.JSON(200, gin.H{
"news": news,
})
}
func NewsDelete(c *gin.Context) {
// Get id
id := c.Param("id")
// Delete
initializers.DB.Delete(&models.News{}, id)
// Response
c.Status(200)
}

38
controllers/postsController.go

@ -8,90 +8,86 @@ import (
) )
func PostsCreate(c *gin.Context) { func PostsCreate(c *gin.Context) {
// Get data // Get data off req body
var body struct { var body struct {
Body string Body string
Title string Title string
} }
c.Bind(&body) c.Bind(&body)
// Create a post // Create a post
post := models.Post{Title: body.Title, Body: body.Body} post := models.Post{Title: body.Title, Body: body.Body}
result := initializers.DB.Create(&post) result := initializers.DB.Create(&post)
if result.Error != nil { if result.Error != nil {
c.Status(400) c.Status(400)
return return
} }
// Return it
// Return
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"post": post, "post": post,
}) })
} }
func PostsIndex(c *gin.Context) { func PostsIndex(c *gin.Context) {
// Get post // Get the posts
var posts []models.Post var posts []models.Post
initializers.DB.Find(&posts) initializers.DB.Find(&posts)
// Response // Respond with them
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"posts": posts, "post": posts,
}) })
} }
func PostsShow(c *gin.Context) { func PostsShow(c *gin.Context) {
// Get id // Get id off URL
id := c.Param("id") id := c.Param("id")
// Get the post // Get the posts
var post models.Post var post models.Post
initializers.DB.First(&post, id) initializers.DB.First(&post, id)
// Response // Respond with them
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"post": post, "post": post,
}) })
} }
func PostsUpdate(c *gin.Context) { func PostsUpdate(c *gin.Context) {
// Get id // Get the id off the URL
id := c.Param("id") id := c.Param("id")
// Get data // Get the data off req body
var body struct { var body struct {
Body string Body string
Title string Title string
} }
c.Bind(&body) c.Bind(&body)
// find // Find the post were updating
var post models.Post var post models.Post
initializers.DB.First(&post, id) initializers.DB.First(&post, id)
//Update // Update it
initializers.DB.Model(&post).Updates(models.Post{ initializers.DB.Model(&post).Updates(models.Post{
Title: body.Title, Title: body.Title,
Body: body.Body, Body: body.Body,
}) })
// Response // Respond with it
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"post": post, "post": post,
}) })
} }
func PostDelete(c *gin.Context) { func PostsDelete(c *gin.Context) {
// Get id // Get the id off the URL
id := c.Param("id") id := c.Param("id")
// Delete // Delete the post
initializers.DB.Delete(&models.Post{}, id) initializers.DB.Delete(&models.Post{}, id)
// Response // Respond
c.Status(200) c.Status(200)
} }

20
controllers/usersControllers.go → controllers/usersController.go

@ -1,18 +1,19 @@
package controllers package controllers
import ( import (
"go-crud/initializers"
"go-crud/models"
"net/http" "net/http"
"os" "os"
"time" "time"
"go-crud/initializers"
"go-crud/models"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
func Signup(c *gin.Context) { func SignUp(c *gin.Context) {
// Get the email/pass off req body // Get the email/pass off req body
var body struct { var body struct {
Email string Email string
@ -49,7 +50,7 @@ func Signup(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{}) c.JSON(http.StatusOK, gin.H{})
} }
func Login(c *gin.Context) { func LogIn(c *gin.Context) {
// Get the email/pass off req body // Get the email/pass off req body
var body struct { var body struct {
Email string Email string
@ -106,6 +107,17 @@ func Login(c *gin.Context) {
}) })
} }
func LogOut (c *gin.Context){
// Hapus informasi autentikasi atau sesi dari pengguna (misalnya token, cookie, atau data sesi)
// Contoh: Hapus cookie autentikasi
c.SetCookie("Authorization", "", -1, "/", "", false, true)
// Berikan respons berhasil logout
c.JSON(http.StatusOK, gin.H{
"message": "Logout successful",
})
}
func Validate(c *gin.Context) { func Validate(c *gin.Context) {
user, _ := c.Get("user") user, _ := c.Get("user")

BIN
go-crud.exe

Binary file not shown.

BIN
go-crud.exe~

Binary file not shown.

30
go.mod

@ -2,32 +2,33 @@ module go-crud
go 1.20 go 1.20
require github.com/gin-gonic/gin v1.9.1 require gorm.io/driver/postgres v1.5.2
require ( require (
github.com/bytedance/sonic v1.9.1 // indirect github.com/bytedance/sonic v1.9.2 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/fatih/color v1.15.0 // indirect github.com/fatih/color v1.9.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.9.1 // indirect
github.com/githubnemo/CompileDaemon v1.4.0 // indirect github.com/githubnemo/CompileDaemon v1.4.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect github.com/go-playground/validator/v10 v10.14.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-json v0.10.2 // indirect
github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/golang-jwt/jwt/v4 v4.5.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgx/v5 v5.4.1 // indirect github.com/jackc/pgx/v5 v5.3.1 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect github.com/jinzhu/now v1.1.5 // indirect
github.com/joho/godotenv v1.5.1 // indirect github.com/joho/godotenv v1.5.1 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/leodido/go-urn v1.2.4 // indirect github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-colorable v0.1.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect github.com/mattn/go-isatty v0.0.19 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
@ -36,12 +37,11 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.11.0 // indirect golang.org/x/crypto v0.10.0 // indirect
golang.org/x/net v0.10.0 // indirect golang.org/x/net v0.11.0 // indirect
golang.org/x/sys v0.10.0 // indirect golang.org/x/sys v0.9.0 // indirect
golang.org/x/text v0.11.0 // indirect golang.org/x/text v0.10.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/postgres v1.5.2 // indirect
gorm.io/gorm v1.25.2 // indirect gorm.io/gorm v1.25.2 // indirect
) )

41
go.sum

@ -1,6 +1,6 @@
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= github.com/bytedance/sonic v1.9.2 h1:GDaNjuWSGu09guE9Oql0MSTNhNCLlWwO8y/xM5BzcbM=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/bytedance/sonic v1.9.2/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
@ -10,12 +10,8 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumC
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s=
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
@ -28,8 +24,8 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js= github.com/go-playground/validator/v10 v10.14.1 h1:9c50NUPC30zyuKprjL3vNZ0m5oG+jU0zvx4AqHGnv4k=
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= github.com/go-playground/validator/v10 v10.14.1/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
@ -41,8 +37,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.4.1 h1:oKfB/FhuVtit1bBM3zNRRsZ925ZkMN3HXL+LgLUM9lE= github.com/jackc/pgx/v5 v5.3.1 h1:Fcr8QJ1ZeLi5zsPZqQeUZhNhxfkkKBOgJuYkJHoBOtU=
github.com/jackc/pgx/v5 v5.4.1/go.mod h1:q6iHT8uDNXWiFNOlRqJzBTaSH3+2xCXkokxHZC5qWFY= github.com/jackc/pgx/v5 v5.3.1/go.mod h1:t3JDKnCBlYIc0ewLF0Q7B8MXmoIaBOZj/ic7iHozM/8=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
@ -52,18 +48,15 @@ github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwA
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg=
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA= github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM= github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@ -95,30 +88,22 @@ golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM= golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM=
golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I=
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= golang.org/x/net v0.11.0 h1:Gi2tvZIJyBtO9SDr1q9h5hEQCp/4L2RQ+ar0qjx2oNU=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= golang.org/x/net v0.11.0/go.mod h1:2L/ixqYpgIVXmeoSA/4Lu7BzTG4KIyPIryS4IsOd1oQ=
golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s= golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.10.0 h1:UpjohKhiEgNc0CSauXmwYftY1+LlaC75SJwh0SgCX58= golang.org/x/text v0.10.0 h1:UpjohKhiEgNc0CSauXmwYftY1+LlaC75SJwh0SgCX58=
golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4=
golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

13
initializers/database.go

@ -1,21 +1,22 @@
package initializers package initializers
import ( import(
"log" "log"
"os" "os"
"gorm.io/driver/postgres"
"gorm.io/gorm" "gorm.io/gorm"
) "gorm.io/driver/postgres"
)
var DB *gorm.DB var DB *gorm.DB
func ConnectToDB() { func ConnectToDB(){
var err error var err error
dsn := os.Getenv("DB_URL") dsn := os.Getenv("DB_URL")
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil { if err != nil{
log.Fatal("Failed to connect to database") log.Fatal("Failed to connect to database")
} }
} }

10
initializers/loadEnvVariables.go

@ -1,15 +1,13 @@
package initializers package initializers
import ( import(
"log" "log"
"github.com/joho/godotenv" "github.com/joho/godotenv"
) )
func LoadEnvVariables() { func LoadEnvVariables(){
err := godotenv.Load() err := godotenv.Load()
if err != nil{
if err != nil {
log.Fatal("Error loading .env file") log.Fatal("Error loading .env file")
} }
} }

4
initializers/syncDatabase.go

@ -3,5 +3,7 @@ package initializers
import "go-crud/models" import "go-crud/models"
func SyncDatabase() { func SyncDatabase() {
DB.AutoMigrate(&models.Post{})
DB.AutoMigrate(&models.Event{})
DB.AutoMigrate(&models.User{}) DB.AutoMigrate(&models.User{})
} }

25
main.go

@ -13,26 +13,25 @@ func init() {
initializers.ConnectToDB() initializers.ConnectToDB()
initializers.SyncDatabase() initializers.SyncDatabase()
} }
func main() { func main() {
r := gin.Default() r := gin.Default()
r.POST("/signup", controllers.Signup) r.POST("/signup", controllers.SignUp)
r.POST("/login", controllers.Login) r.POST("/login", controllers.LogIn)
r.GET("/validate", middleware.RequireAuth, controllers.Validate) r.GET("/validate", middleware.RequireAuth, controllers.Validate)
r.Use(middleware.RequireAuth)
r.POST("/posts", controllers.PostsCreate) r.POST("/posts", controllers.PostsCreate)
r.PUT("/posts/:id", controllers.PostsUpdate)
r.GET("/posts", controllers.PostsIndex) r.GET("/posts", controllers.PostsIndex)
r.GET("/posts/:id", controllers.PostsShow) r.GET("/posts/:id", controllers.PostsShow)
r.PUT("/posts/:id", controllers.PostsUpdate) r.DELETE("/posts/:id", controllers.PostsDelete)
r.DELETE("/posts/:id", controllers.PostDelete)
r.Use(middleware.RequireAuth) r.POST("/events", controllers.EventsCreate)
r.POST("/news", controllers.NewsCreate) r.PUT("/events/:id", controllers.EventsUpdate)
r.GET("/newsData", controllers.NewsIndex) r.GET("/events", controllers.EventsIndex)
r.GET("/newsShow/:id", controllers.NewsShow) r.GET("/events/:id", controllers.EventsShow)
r.PUT("/newsUpdate/:id", controllers.NewsUpdate) r.DELETE("/events/:id", controllers.EventsDelete)
r.DELETE("/newsDelete/:id", controllers.NewsDelete)
r.Run() r.Run() // listen and serve on 0.0.0.0:8080
} }

21
middleware/requireAuth.go

@ -17,7 +17,7 @@ func RequireAuth(c *gin.Context) {
// Get the cookie off req // Get the cookie off req
tokenString, err := c.Cookie("Authorization") tokenString, err := c.Cookie("Authorization")
if err != nil { if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Anda belum login"}) c.AbortWithStatus(http.StatusUnauthorized)
return return
} }
@ -32,19 +32,19 @@ func RequireAuth(c *gin.Context) {
}) })
if err != nil || !token.Valid { if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token tidak valid"}) c.AbortWithStatus(http.StatusUnauthorized)
return return
} }
claims, ok := token.Claims.(jwt.MapClaims) claims, ok := token.Claims.(jwt.MapClaims)
if !ok { if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token tidak valid"}) c.AbortWithStatus(http.StatusUnauthorized)
return return
} }
// Check the exp // Check the exp
if exp, ok := claims["exp"].(float64); ok && float64(time.Now().Unix()) > exp { if exp, ok := claims["exp"].(float64); ok && float64(time.Now().Unix()) > exp {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token kedaluwarsa"}) c.AbortWithStatus(http.StatusUnauthorized)
return return
} }
@ -52,16 +52,17 @@ func RequireAuth(c *gin.Context) {
var user models.User var user models.User
initializers.DB.First(&user, claims["sub"]) initializers.DB.First(&user, claims["sub"])
var post models.Post
initializers.DB.First(&post, claims["sub"])
var event models.Event
initializers.DB.First(&event, claims["sub"])
if user.ID == 0 { if user.ID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User tidak ditemukan"}) c.AbortWithStatus(http.StatusUnauthorized)
return return
} }
// Check user's level
if user.Email != "dave@gmail." {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Anda tidak memiliki akses yang cukup"})
return
}
// Attach to req // Attach to req
c.Set("user", user) c.Set("user", user)

16
migrate/migrate.go

@ -1,16 +0,0 @@
package main
import (
"go-crud/initializers"
"go-crud/models"
)
func init() {
initializers.LoadEnvVariables()
initializers.ConnectToDB()
}
func main() {
initializers.DB.AutoMigrate(&models.Post{})
initializers.DB.AutoMigrate(&models.News{})
}

16
models/eventModel.go

@ -0,0 +1,16 @@
package models
import (
"time"
"gorm.io/gorm"
)
type Event struct {
gorm.Model
Name string
Content string
PostBy string
Category string
Date *time.Time
}

13
models/newsModels.go

@ -1,13 +0,0 @@
package models
import "time"
type News struct {
ID int `gorm:"primaryKey"`
Title string `gorm:"size:255"`
Content string `gorm:"type:text"`
Author string `gorm:"size:255"`
Date time.Time `gorm:"type:date"`
CreatedBy string `gorm:"size:255"`
CreatedAt time.Time `gorm:"type:timestamp"`
}

4
models/postModels.go → models/postModel.go

@ -5,5 +5,5 @@ import "gorm.io/gorm"
type Post struct { type Post struct {
gorm.Model gorm.Model
Title string Title string
Body string Body string
} }

0
models/userModels.go → models/userModel.go

Loading…
Cancel
Save