-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #10 from Sardonyx001/feat/add-model-services
feat: 各種モデルストアをアクセスするサービスを追加した
- Loading branch information
Showing
27 changed files
with
967 additions
and
45 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package config | ||
|
||
import ( | ||
"os" | ||
|
||
validation "github.com/go-ozzo/ozzo-validation/v4" | ||
"github.com/golang-jwt/jwt/v4" | ||
) | ||
|
||
type AuthConfig struct { | ||
AccessSecret string | ||
RefreshSecret string | ||
} | ||
|
||
func LoadAuthConfig() AuthConfig { | ||
return AuthConfig{ | ||
AccessSecret: os.Getenv("ACCESS_SECRET"), | ||
RefreshSecret: os.Getenv("REFRESH_SECRET"), | ||
} | ||
} | ||
|
||
type BasicAuth struct { | ||
Username string `json:"username" validate:"required" example:"test_username"` | ||
Password string `json:"password" validate:"required" example:"test_password"` | ||
} | ||
|
||
func (ba BasicAuth) Validate() error { | ||
return validation.ValidateStruct(&ba, | ||
validation.Field(&ba.Username, validation.Length(8, 255)), | ||
validation.Field(&ba.Password, validation.Length(8, 255)), | ||
) | ||
} | ||
|
||
type JwtCustomClaims struct { | ||
ID string `json:"id"` | ||
Admin bool `json:"admin"` | ||
jwt.RegisteredClaims | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package logger | ||
|
||
import "go.uber.org/zap" | ||
|
||
var zapLogger *zap.Logger | ||
|
||
func New() error { | ||
logger, err := zap.NewProduction() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
zapLogger = logger | ||
|
||
return nil | ||
} | ||
|
||
func Debug(msg string, fields ...zap.Field) { | ||
zapLogger.Debug(msg, fields...) | ||
} | ||
|
||
func Info(msg string, fields ...zap.Field) { | ||
zapLogger.Info(msg, fields...) | ||
} | ||
|
||
func Warn(msg string, fields ...zap.Field) { | ||
zapLogger.Warn(msg, fields...) | ||
} | ||
|
||
func Error(msg string, fields ...zap.Field) { | ||
zapLogger.Error(msg, fields...) | ||
} | ||
|
||
func Fatal(msg string, fields ...zap.Field) { | ||
zapLogger.Fatal(msg, fields...) | ||
} | ||
|
||
func Sync() { | ||
_ = zapLogger.Sync() | ||
} | ||
|
||
func Delete() { | ||
zapLogger = nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package middlewares | ||
|
||
import ( | ||
"backend/config" | ||
"backend/stores" | ||
"net/http" | ||
|
||
"github.com/golang-jwt/jwt/v4" | ||
"github.com/labstack/echo/v4" | ||
) | ||
|
||
type AuthMiddleware struct { | ||
store *stores.Stores | ||
} | ||
|
||
func NewAuthMw(store *stores.Stores) AuthMiddleware { | ||
return AuthMiddleware{ | ||
store: store, | ||
} | ||
} | ||
|
||
func (m *AuthMiddleware) RestaurantAccess() echo.MiddlewareFunc { | ||
return func(next echo.HandlerFunc) echo.HandlerFunc { | ||
return func(c echo.Context) error { | ||
restaurant_id := c.Param("restaurant_id") | ||
|
||
token := c.Get("user").(*jwt.Token) | ||
claims := token.Claims.(*config.JwtCustomClaims) | ||
|
||
user, err := m.store.User.GetById(claims.ID) | ||
if err != nil { | ||
return echo.NewHTTPError(http.StatusUnauthorized, "Access Denied") | ||
} | ||
|
||
// UserがこのRestaurantにアクセスできる権限があるかどうかを確認 | ||
isOwner := false | ||
for _, r := range user.Restaurants { | ||
if restaurant_id == r.ID { | ||
isOwner = true | ||
break | ||
} | ||
} | ||
|
||
if !isOwner { | ||
return echo.NewHTTPError(http.StatusUnauthorized, "Access Denied") | ||
} | ||
|
||
return next(c) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package handlers | ||
|
||
import ( | ||
"backend/config" | ||
"backend/services" | ||
"backend/utils" | ||
"net/http" | ||
|
||
"github.com/labstack/echo/v4" | ||
) | ||
|
||
type ( | ||
AdminHandler interface { | ||
GetAdminById(c echo.Context) error | ||
CreateAdmin(c echo.Context) error | ||
UpdateAdminById(c echo.Context) error | ||
DeleteAdminById(c echo.Context) error | ||
} | ||
|
||
adminHandler struct { | ||
services.AdminService | ||
} | ||
) | ||
|
||
func (h *adminHandler) GetAdminById(c echo.Context) error { | ||
userID := c.Param("id") | ||
user, err := h.AdminService.GetAdminById(userID) | ||
if err != nil { | ||
|
||
return c.JSON(http.StatusNotFound, utils.Error{Message: err.Error()}) | ||
} | ||
return c.JSON(http.StatusOK, user) | ||
} | ||
|
||
func (h *adminHandler) CreateAdmin(c echo.Context) error { | ||
userAuth := new(config.BasicAuth) | ||
|
||
if err := c.Bind(userAuth); err != nil { | ||
return c.JSON(http.StatusBadRequest, "Request doesn't match schema") | ||
} | ||
|
||
if err := userAuth.Validate(); err != nil { | ||
return c.JSON(http.StatusBadRequest, "Required fields are empty or not valid") | ||
} | ||
|
||
_, err := h.AdminService.GetAdminByUsername(userAuth.Username) | ||
|
||
if err == nil { | ||
return c.JSON(http.StatusBadRequest, "User already exists") | ||
} | ||
|
||
userId, err := h.AdminService.CreateAdmin(userAuth) | ||
if err != nil { | ||
return c.JSON(http.StatusInternalServerError, "Server error") | ||
} | ||
|
||
return c.JSON(http.StatusCreated, userId) | ||
|
||
} | ||
|
||
func (h *adminHandler) UpdateAdminById(c echo.Context) error { | ||
return c.JSON(http.StatusOK, "UpdateUserById") | ||
} | ||
|
||
func (h *adminHandler) DeleteAdminById(c echo.Context) error { | ||
return c.JSON(http.StatusOK, "Called DeleteUserById") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
package handlers | ||
|
||
import ( | ||
"backend/config" | ||
"backend/logger" | ||
"backend/services" | ||
"net/http" | ||
|
||
"github.com/labstack/echo/v4" | ||
"go.uber.org/zap" | ||
"golang.org/x/crypto/bcrypt" | ||
) | ||
|
||
type ( | ||
AuthHandler interface { | ||
LoginForUser(c echo.Context) error | ||
LoginForAdmin(c echo.Context) error | ||
} | ||
|
||
authHandler struct { | ||
services.AuthService | ||
services.UserService | ||
services.AdminService | ||
} | ||
) | ||
|
||
func (h *authHandler) LoginForUser(c echo.Context) error { | ||
userAuth := new(config.BasicAuth) | ||
|
||
if err := c.Bind(userAuth); err != nil { | ||
return c.JSON(http.StatusBadRequest, "Request doesn't match schema") | ||
} | ||
|
||
if err := userAuth.Validate(); err != nil { | ||
return c.JSON(http.StatusBadRequest, "Required fields are empty or not valid") | ||
} | ||
|
||
user, err := h.UserService.GetUserByUsername(userAuth.Username) | ||
if err != nil || (bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(userAuth.Password)) != nil) { | ||
return c.JSON(http.StatusUnauthorized, "Invalid credentials") | ||
} | ||
|
||
accessToken, _, err := h.AuthService.GenerateAccessToken(user.ID, false) | ||
if err != nil { | ||
logger.Error("Failed to authenticate: ", zap.Error(err)) | ||
return c.JSON(http.StatusUnauthorized, "Invalid credentials") | ||
} | ||
|
||
return c.JSON(http.StatusOK, map[string]string{ | ||
"token": accessToken, | ||
}) | ||
} | ||
|
||
func (h *authHandler) LoginForAdmin(c echo.Context) error { | ||
userAuth := new(config.BasicAuth) | ||
|
||
if err := c.Bind(userAuth); err != nil { | ||
return c.JSON(http.StatusBadRequest, "Request doesn't match schema") | ||
} | ||
|
||
if err := userAuth.Validate(); err != nil { | ||
return c.JSON(http.StatusBadRequest, "Required fields are empty or not valid") | ||
} | ||
|
||
admin, err := h.AdminService.GetAdminByUsername(userAuth.Username) | ||
if err != nil || (bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(userAuth.Password)) != nil) { | ||
return c.JSON(http.StatusUnauthorized, "Invalid credentials") | ||
} | ||
|
||
accessToken, _, err := h.AuthService.GenerateAccessToken(admin.ID, true) | ||
if err != nil { | ||
logger.Error("Failed to authenticate: ", zap.Error(err)) | ||
return c.JSON(http.StatusUnauthorized, "Invalid credentials") | ||
} | ||
|
||
return c.JSON(http.StatusOK, map[string]string{ | ||
"token": accessToken, | ||
}) | ||
} |
Oops, something went wrong.