moved changes from identity - they must bo pushed to rest-api-prototype repo...
This commit is contained in:
parent
2e14d614f0
commit
f422fda254
@ -14,9 +14,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
defHttpIp = "127.0.0.1"
|
defHttpIp = "0.0.0.0"
|
||||||
defHttpPort = "8080"
|
defHttpPort = "8080"
|
||||||
defDbUrl = "postgres://postgres:postgres@127.0.0.1:5432/Api" // FIXME: use env
|
defDbUrl = "postgres://postgres:12345678@127.0.0.1:5432/egommerce"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@ -24,10 +24,8 @@ func main() {
|
|||||||
app.Panicf("Error loading .env file")
|
app.Panicf("Error loading .env file")
|
||||||
}
|
}
|
||||||
|
|
||||||
httpAddr := net.JoinHostPort(config.GetEnv("SERVER_IP", defHttpIp), config.GetEnv("SERVER_PORT", defHttpPort))
|
httpAddr := net.JoinHostPort(config.GetEnv("SERVER_IP", defHttpIp), defHttpPort)
|
||||||
dbConnStr := config.GetEnv("DATABASE_URL", defDbUrl)
|
dbConnStr := config.GetEnv("DATABASE_URL", defDbUrl)
|
||||||
//fmt.Println(dbConnStr)
|
|
||||||
//os.Exit(1)
|
|
||||||
|
|
||||||
dbc, err := database.Connect(dbConnStr)
|
dbc, err := database.Connect(dbConnStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -1,9 +0,0 @@
|
|||||||
package definition
|
|
||||||
|
|
||||||
type AuthLoginRequest struct {
|
|
||||||
Username string `json:"username"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type AuthLoginResponse struct {
|
|
||||||
}
|
|
@ -1,18 +0,0 @@
|
|||||||
package entity
|
|
||||||
|
|
||||||
import "time"
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
ID int `json:"id"`
|
|
||||||
Username string `json:"username"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
CreateDate time.Time `json:"create_date"`
|
|
||||||
ModifyDate time.Time `json:"modify_date"` // FIXME: zero-value issue
|
|
||||||
}
|
|
||||||
|
|
||||||
var TestUser = &User{
|
|
||||||
ID: 1,
|
|
||||||
Username: "test",
|
|
||||||
Password: "test",
|
|
||||||
CreateDate: time.Now(),
|
|
||||||
}
|
|
@ -1,35 +0,0 @@
|
|||||||
package handler
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
def "git.pbiernat.dev/egommerce/basket-service/internal/app/definition"
|
|
||||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/service"
|
|
||||||
)
|
|
||||||
|
|
||||||
var AuthLoginHandler *Handler
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
AuthLoginHandler = &Handler{
|
|
||||||
Handle: AuthLoginHandlerFunc,
|
|
||||||
Request: &def.AuthLoginRequest{},
|
|
||||||
Response: &def.AuthLoginResponse{},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func AuthLoginHandlerFunc(h *Handler, w http.ResponseWriter) (interface{}, int, error) {
|
|
||||||
var req = h.Request.(*def.AuthLoginRequest)
|
|
||||||
// u := entity.TestUser
|
|
||||||
|
|
||||||
token, err := service.AuthService.Login(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, http.StatusUnauthorized, err
|
|
||||||
}
|
|
||||||
|
|
||||||
service.AuthService.SetCookie(w, service.AuthService.TokenCookieName, token)
|
|
||||||
// service.AuthService.SetCookie(w, service.AuthService.RefreshTokenCookieName, refreshTtoken)
|
|
||||||
|
|
||||||
// log.Println("user:", u, "req:", token, "err:", err)
|
|
||||||
|
|
||||||
return nil, http.StatusOK, nil
|
|
||||||
}
|
|
@ -16,11 +16,7 @@ func SetupRouter(env *handler.Env) *mux.Router {
|
|||||||
r.Use(ValidateJsonBodyMiddleware) // probably not needed
|
r.Use(ValidateJsonBodyMiddleware) // probably not needed
|
||||||
r.Use(LoggingMiddleware)
|
r.Use(LoggingMiddleware)
|
||||||
|
|
||||||
hc := r.PathPrefix("/health").Subrouter()
|
r.Handle("/health", handler.Init(env, handler.HealthCheckHandler)).Methods(http.MethodGet)
|
||||||
hc.Handle("", handler.Init(env, handler.HealthCheckHandler)).Methods(http.MethodGet)
|
|
||||||
|
|
||||||
auth := r.PathPrefix("/auth").Subrouter()
|
|
||||||
auth.Handle("/login", handler.Init(env, handler.AuthLoginHandler)).Methods(http.MethodPost)
|
|
||||||
|
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
@ -1,113 +0,0 @@
|
|||||||
package service
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/config"
|
|
||||||
def "git.pbiernat.dev/egommerce/basket-service/internal/app/definition"
|
|
||||||
"github.com/golang-jwt/jwt"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
AuthService *Auth
|
|
||||||
|
|
||||||
ErrUserNotFound = errors.New("user not found")
|
|
||||||
ErrTokenError = errors.New("failed to generate JWT token")
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
expire, _ := strconv.Atoi(config.GetEnv("AUTH_TOKEN_EXPIRE_TIME", "5"))
|
|
||||||
secret := []byte(config.GetEnv("AUTH_SECRET_HMAC", "B413IlIv9nKQfsMCXTE0Cteo4yHgUEfqaLfjg73sNlh"))
|
|
||||||
|
|
||||||
AuthService = &Auth{expire, "jwt_token", "jwt_token_refresh", secret}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Auth struct {
|
|
||||||
ExpireTime int // token expire time in minutes
|
|
||||||
TokenCookieName string
|
|
||||||
RefreshTokenCookieName string
|
|
||||||
|
|
||||||
secret []byte // signing key
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Auth) Login(r *def.AuthLoginRequest) (string, error) {
|
|
||||||
if r.Username == "admin" && r.Password == "secret" {
|
|
||||||
token, err := a.createToken()
|
|
||||||
if err != nil {
|
|
||||||
return "", ErrTokenError
|
|
||||||
}
|
|
||||||
|
|
||||||
return token, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return "", ErrUserNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetCookie appends cookie header to response
|
|
||||||
func (a *Auth) SetCookie(w http.ResponseWriter, name, token string) {
|
|
||||||
c := &http.Cookie{
|
|
||||||
Name: name,
|
|
||||||
Value: token,
|
|
||||||
MaxAge: a.ExpireTime * 60,
|
|
||||||
Path: "/",
|
|
||||||
}
|
|
||||||
http.SetCookie(w, c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a Auth) createToken() (string, error) {
|
|
||||||
// log.Println("now:", time.Now().Unix())
|
|
||||||
// log.Println("expire at:", time.Now().Add(time.Duration(a.ExpireTime)*time.Minute).Unix())
|
|
||||||
claims := &jwt.StandardClaims{
|
|
||||||
ExpiresAt: time.Now().Add(time.Duration(a.ExpireTime) * time.Minute).Unix(),
|
|
||||||
}
|
|
||||||
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
||||||
return token.SignedString(a.secret)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Auth) validateToken(tokenStr string) error {
|
|
||||||
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
|
|
||||||
// Don't forget to validate the alg is what you expect:
|
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
||||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
|
||||||
}
|
|
||||||
|
|
||||||
// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
|
|
||||||
return a.secret, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
||||||
log.Println(claims)
|
|
||||||
} else {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a Auth) ValidateUserTokenMiddleware(next http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
cToken, err := r.Cookie(a.TokenCookieName)
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
json.NewEncoder(w).Encode(def.Error("Missing JWT Token cookie"))
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := a.validateToken(cToken.Value); err != nil {
|
|
||||||
w.WriteHeader(http.StatusUnauthorized)
|
|
||||||
json.NewEncoder(w).Encode(def.Error(err.Error()))
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
next.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
Loading…
Reference in New Issue
Block a user