Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
devkuros committed Apr 5, 2022
0 parents commit c0d428f
Show file tree
Hide file tree
Showing 15 changed files with 720 additions and 0 deletions.
19 changes: 19 additions & 0 deletions configs/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package configs

import (
"mygram/models"

"gorm.io/driver/postgres"
"gorm.io/gorm"
)

func Conns() *gorm.DB {
dsn := "host=localhost user=postgres password=root dbname=mygramdb port=5432 sslmode=disable TimeZone=Asia/Jakarta"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect to database")
}

db.Debug().AutoMigrate(models.User{}, models.Photo{}, models.Comment{}, models.SocialMedia{})
return db
}
37 changes: 37 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
module mygram

go 1.18

require (
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.7.7 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.10.1 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.11.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.2.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.10.0 // indirect
github.com/jackc/pgx/v4 v4.15.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 // indirect
golang.org/x/sys v0.0.0-20220403205710-6acee93ad0eb // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gorm.io/driver/postgres v1.3.3 // indirect
gorm.io/gorm v1.23.4 // indirect
)
249 changes: 249 additions & 0 deletions go.sum

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions handlers/bcrypt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package handlers

import "golang.org/x/crypto/bcrypt"

func HashPassword(p string) string {
salt := 8
password := []byte(p)
hash, _ := bcrypt.GenerateFromPassword(password, salt)

return string(hash)
}

func ComparePassword(h, p []byte) bool {
err := bcrypt.CompareHashAndPassword([]byte(h), []byte(p))

return err == nil
}
7 changes: 7 additions & 0 deletions handlers/header_value.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package handlers

import "github.com/gin-gonic/gin"

func GetContentType(c *gin.Context) string {
return c.Request.Header.Get("Content-Type")
}
46 changes: 46 additions & 0 deletions handlers/jwt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package handlers

import (
"errors"
"strings"

"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)

var secretKey = "rahasia"

func GenerateToken(id uint, email string) string {
claims := jwt.MapClaims{
"id": id,
"email": email,
}

parseToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, _ := parseToken.SignedString([]byte(secretKey))
return signedToken
}

func VerifyToken(c *gin.Context) (interface{}, error) {
errResponse := errors.New("Sign in to proses")
headerToken := c.Request.Header.Get("Authorization")

bearer := strings.HasPrefix(headerToken, "Bearer")
if !bearer {
return nil, errResponse
}

stringToken := strings.Split(headerToken, " ")[1]
token, _ := jwt.Parse(stringToken, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errResponse
}
return []byte(secretKey), nil
})

if _, ok := token.Claims.(jwt.MapClaims); !ok && !token.Valid {
return nil, errResponse
}

return token.Claims.(jwt.MapClaims), nil
}
8 changes: 8 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package main

import "mygram/routers"

func main() {
r := routers.StartServer()
r.Run(":8080")
}
26 changes: 26 additions & 0 deletions middlewares/authentication.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package middlewares

import (
"mygram/handlers"
"net/http"

"github.com/gin-gonic/gin"
)

func Authentication() gin.HandlerFunc {
return func(c *gin.Context) {
verifyToken, err := handlers.VerifyToken(c)
// fmt.Println("ni verify token", verifyToken)

if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "Unauthorized",
"message": err.Error(),
})
return
}

c.Set("userData", verifyToken)
c.Next()
}
}
57 changes: 57 additions & 0 deletions middlewares/user_authorization.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package middlewares

import (
"mygram/models"
"net/http"
"strconv"

"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"gorm.io/gorm"
)

type userAuthorization struct {
DB *gorm.DB
}

func NewUserAuthorization(db *gorm.DB) *userAuthorization {
return &userAuthorization{
DB: db,
}
}

func (ua *userAuthorization) UserAuthorizations() gin.HandlerFunc {
return func(c *gin.Context) {
getId, err := strconv.Atoi(c.Param("userId"))
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"error": "Bad Request",
"message": "invalid parameter",
})
return
}

userData := c.MustGet("userData").(jwt.MapClaims)
userID := uint(userData["id"].(float64))

User := models.User{}

err = ua.DB.Select("id").First(&User, uint(getId)).Error
if err != nil {
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{
"error": "Data not found",
"message": "data not exist",
})
return
}

if User.ID != userID {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "Unauthorized",
"message": "please try again!",
})
return
}
c.Next()
}
}
25 changes: 25 additions & 0 deletions models/comments_models.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package models

import (
"github.com/asaskevich/govalidator"
"gorm.io/gorm"
)

type Comment struct {
gorm.Model
UserID uint
User *User `json:"user" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
PhotoID uint
Photo *Photo `json:"photo" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
Message string `json:"message" gorm:"not null" valid:"required~Leave a comment messages"`
}

func (cmn *Comment) BeforeCreate(tx *gorm.DB) (err error) {
if _, errCreate := govalidator.ValidateStruct(cmn); errCreate != nil {
err = errCreate
return
}

err = nil
return
}
25 changes: 25 additions & 0 deletions models/photos_models.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package models

import (
"github.com/asaskevich/govalidator"
"gorm.io/gorm"
)

type Photo struct {
gorm.Model
Tittle string `json:"tittle" gorm:"not null" form:"tittle" valid:"required~Input Tittle"`
Caption string `json:"caption" form:"caption"`
PhotoUrl string `json:"photo_url" gorm:"not null" valid:"required~Input Photo URL"`
UserID uint
User *User
}

func (ph *Photo) BeforeCreate(tx *gorm.DB) (err error) {
if _, errCreate := govalidator.ValidateStruct(ph); errCreate != nil {
err = errCreate
return
}

err = nil
return
}
24 changes: 24 additions & 0 deletions models/socialmedias_models.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package models

import (
"github.com/asaskevich/govalidator"
"gorm.io/gorm"
)

type SocialMedia struct {
gorm.Model
Nama string `json:"nama" gorm:"not null" valid:"required~Input Name"`
SocialMediaUrl string `json:"social_media_url" gorm:"not null" valid:"required~Input Social Media URL"`
UserID uint
User *User `json:"user" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

func (sm *SocialMedia) BeforeCreate(tx *gorm.DB) (err error) {
if _, errCreate := govalidator.ValidateStruct(sm); errCreate != nil {
err = errCreate
return
}

err = nil
return
}
28 changes: 28 additions & 0 deletions models/users_models.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package models

import (
"mygram/handlers"

"github.com/asaskevich/govalidator"
"gorm.io/gorm"
)

type User struct {
gorm.Model
Username string `json:"username" gorm:"not null;unique" form:"username" valid:"required~Input Username"`
Email string `json:"email" gorm:"not null;unique" form:"email" valid:"required~Email required,email~Invalid email format"`
Password string `json:"password" gorm:"not null" form:"password" valid:"required~Input Password,minstringlength(6)~Password has to have a minimum length of 6 characters"`
Age int `json:"age" gorm:"not null" form:"age" valid:"required~Input Age,range(8|130)~Min Age 8"`
Photo []Photo `json:"photo" gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
if _, errCreate := govalidator.ValidateStruct(u); errCreate != nil {
err = errCreate
return
}

u.Password = handlers.HashPassword(u.Password)
err = nil
return
}
Loading

0 comments on commit c0d428f

Please sign in to comment.