Token

Membuat token auth menggunakan jwt token.

  • Tambahkan TOKEN_SALT environtment pada file .env

APP_PORT=9000
APP_ENV=local

DB_DRIVER=mysql
DB_SOURCE=root:pass@tcp(localhost:3306)/go-services?parseTime=true

TOKEN_SALT=secret-salt
  • Membuat token library pada libraries/token/token.go

package token

import (
    "os"
    "time"

    jwt "github.com/dgrijalva/jwt-go"
)

// MyCustomClaims struct
type MyCustomClaims struct {
    Username string `json:"username"`
    jwt.StandardClaims
}

var mySigningKey = []byte(os.Getenv("TOKEN_SALT"))

// ValidateToken for check token validation
func ValidateToken(myToken string) (bool, string) {
    token, err := jwt.ParseWithClaims(myToken, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte(mySigningKey), nil
    })

    if err != nil {
        return false, ""
    }

    claims := token.Claims.(*MyCustomClaims)
    return token.Valid, claims.Username
}

// ClaimToken function
func ClaimToken(username string) (string, error) {
    claims := MyCustomClaims{
        username,
        jwt.StandardClaims{
            ExpiresAt: time.Now().Add(time.Hour * 5).Unix(),
        },
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

    // Sign the token with our secret
    return token.SignedString(mySigningKey)
}
  • Tambahkan login routing pada routing/route.go

  • Buat controllers auths pada controllers/auths.go

  • Buat payload login request pada payloads/request/login_request.go

  • Buat GetByUsername method pada models/user.go

  • Buat payload token response pada payloads/response/token_response.go

  • Buat api test untuk login. Buat file controllers/tests/authstest.go

  • Update tests/main_test.go untuk mengetes login

Last updated

Was this helpful?