add authgurad

This commit is contained in:
2024-06-21 18:54:06 +07:00
parent 5826d72988
commit c771187889
15 changed files with 127 additions and 94 deletions

20
auth/jwt.go Normal file
View File

@@ -0,0 +1,20 @@
package auth
import (
"net/http"
echojwt "github.com/labstack/echo-jwt/v4"
"github.com/labstack/echo/v4"
)
var IsLoggedIn = echojwt.WithConfig(
echojwt.Config{
SigningKey: []byte("--one_api-secret-2019-04-01"),
TokenLookup: "cookie:token",
ErrorHandler: JWTErrorChecker,
},
)
func JWTErrorChecker(c echo.Context, err error) error {
return c.Redirect(http.StatusTemporaryRedirect, "/login")
}

View File

@@ -1,7 +0,0 @@
package auth
import "github.com/labstack/echo/v4/middleware"
var IsLoggedIn = middleware.JWTWithConfig(middleware.JWTConfig{
SigningKey: []byte("secret"),
})

View File

@@ -24,16 +24,16 @@ templ Navbaruserprofile(dataUser models.User) {
<div class="separator separator-dashed my-7"></div>
<!--end::Separator-->
<!--begin::Notifications-->
<div>
<!--begin:Heading-->
<h5 class="mb-5">
Recent Notifications
</h5>
<!--end:Heading-->
<!--begin::Item-->
@NotificationCard()
<!--end::Item-->
</div>
// <div>
// <!--begin:Heading-->
// <h5 class="mb-5">
// Recent Notifications
// </h5>
// <!--end:Heading-->
// <!--begin::Item-->
// @NotificationCard()
// <!--end::Item-->
// </div>
<!--end::Notifications-->
</div>
<!--end::Content-->
@@ -55,7 +55,12 @@ templ ProfileHeader(dataUser models.User) {
{ dataUser.UserPosition }
</div>
<div class="navi mt-2">
<a href="#" class="btn btn-sm btn-light-primary font-weight-bolder py-2 px-5">Sign Out</a>
<a
class="btn btn-sm btn-light-primary font-weight-bolder py-2 px-5"
hx-get="/login/signout"
>
Sign Out
</a>
</div>
</div>
</div>

View File

@@ -33,15 +33,7 @@ func Navbaruserprofile(dataUser models.User) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<!--end::Header--><!--begin::Separator--><div class=\"separator separator-dashed my-7\"></div><!--end::Separator--><!--begin::Notifications--><div><!--begin:Heading--><h5 class=\"mb-5\">Recent Notifications\r</h5><!--end:Heading--><!--begin::Item-->")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = NotificationCard().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<!--end::Item--></div><!--end::Notifications--></div><!--end::Content--></div>")
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<!--end::Header--><!--begin::Separator--><div class=\"separator separator-dashed my-7\"></div><!--end::Separator--><!--begin::Notifications--><!--end::Notifications--></div><!--end::Content--></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
@@ -91,7 +83,7 @@ func ProfileHeader(dataUser models.User) templ.Component {
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</div><div class=\"navi mt-2\"><a href=\"#\" class=\"btn btn-sm btn-light-primary font-weight-bolder py-2 px-5\">Sign Out</a></div></div></div>")
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("</div><div class=\"navi mt-2\"><a class=\"btn btn-sm btn-light-primary font-weight-bolder py-2 px-5\" hx-get=\"/login/signout\">Sign Out\r</a></div></div></div>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}

2
go.mod
View File

@@ -7,6 +7,7 @@ require (
github.com/fsnotify/fsnotify v1.7.0
github.com/glebarez/go-sqlite v1.22.0
github.com/go-sql-driver/mysql v1.8.1
github.com/golang-jwt/jwt/v5 v5.0.0
github.com/jmoiron/sqlx v1.4.0
github.com/labstack/echo/v4 v4.12.0
github.com/spf13/viper v1.18.2
@@ -36,6 +37,7 @@ require (
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/labstack/echo-jwt/v4 v4.2.0
github.com/labstack/gommon v0.4.2
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect

4
go.sum
View File

@@ -18,6 +18,8 @@ github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpv
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
github.com/golang-jwt/jwt/v5 v5.0.0 h1:1n1XNM9hk7O9mnQoNBGolZvzebBQ7p93ULHRc28XJUE=
github.com/golang-jwt/jwt/v5 v5.0.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
@@ -32,6 +34,8 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/labstack/echo-jwt/v4 v4.2.0 h1:odSISV9JgcSCuhgQSV/6Io3i7nUmfM/QkBeR5GVJj5c=
github.com/labstack/echo-jwt/v4 v4.2.0/go.mod h1:MA2RqdXdEn4/uEglx0HcUOgQSyBaTh5JcaHIan3biwU=
github.com/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=
github.com/labstack/echo/v4 v4.12.0/go.mod h1:UP9Cr2DJXbOK3Kr9ONYzNowSh7HP0aG0ShAyycHSJvM=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=

View File

@@ -6,13 +6,13 @@ import (
"cpone/component/pagination"
sidebaruserprofile "cpone/component/sidebar_user_profile"
"cpone/models"
"cpone/services"
"cpone/utils"
corporate_dashboardpic "cpone/views/corporate/dashboardpic"
"net/http"
"strconv"
"github.com/a-h/templ"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
)
@@ -40,16 +40,17 @@ func (ea *DashboardPicHandler) HandleShowEmployeeAnalyticScreen(c echo.Context)
listID := utils.GenerateRandomID("listid")
paginationID := utils.GenerateRandomID("paginationid")
// usertoken := c.Get("user").(*jwt.Token)
// claims := usertoken.Claims.(jwt.MapClaims)
// name := claims["M_UserEmail"].(string)
// logger.Info("fromtoken", zap.Any("name", name))
userCok := c.Get("user").(*jwt.Token)
claims := userCok.Claims.(jwt.MapClaims)
name := claims["M_StaffName"].(string)
position := claims["M_UserGroupDashboard"].(string)
logger.Info("jwt", zap.Any("name", name))
user, err := services.GetUserLogin()
if err != nil {
defer logger.Sync()
logger.Info("Error get user dev", zap.Any("error", err))
return err
user := models.User{
UserID: 1,
Username: name,
UserFullName: name,
UserPosition: position,
}
dataBreadcrumb, err := ea.DashboardPicServices.GetEmployeeAnalyticBreadcrumb(title)

View File

@@ -5,11 +5,11 @@ import (
navbarmenu "cpone/component/navbar"
sidebaruserprofile "cpone/component/sidebar_user_profile"
"cpone/models"
"cpone/services"
"cpone/utils"
corporate_mcudetail "cpone/views/corporate/mcu"
corporate_tabmcudetail "cpone/views/corporate/mcu/mcutab"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
)
@@ -30,16 +30,21 @@ func NewMcuDetailHandler(mcud McuDetailServices) *McuDetailHandler {
func (mcud *McuDetailHandler) HandlerShowMcuDetailScreen(c echo.Context) error {
logger, _ := zap.NewProduction()
title := "PT. ABC"
id := c.Param("id")
logger.Info("params", zap.Any("id", id))
user, err := services.GetUserLogin()
if err != nil {
defer logger.Sync()
logger.Info("Error get user corp", zap.Any("error", err))
return err
userCok := c.Get("user").(*jwt.Token)
claims := userCok.Claims.(jwt.MapClaims)
name := claims["M_StaffName"].(string)
position := claims["M_UserGroupDashboard"].(string)
logger.Info("jwt", zap.Any("name", name))
user := models.User{
UserID: 1,
Username: name,
UserFullName: name,
UserPosition: position,
}
dataBreadcrumb, err := mcud.McuDetailServices.GetBreadcrumb(id)
@@ -63,7 +68,7 @@ func (mcud *McuDetailHandler) HandlerShowMcuDetailScreen(c echo.Context) error {
js := corporate_mcudetail.JSMcuDetail()
view := corporate_mcudetail.ShowMcuDetail(
title,
dataBreadcrumb.Title,
content,
css,
js,

View File

@@ -6,11 +6,11 @@ import (
"cpone/component/pagination"
sidebaruserprofile "cpone/component/sidebar_user_profile"
"cpone/models"
"cpone/services"
"cpone/utils"
corporate_patient "cpone/views/corporate/patient"
"strconv"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
)
@@ -125,19 +125,23 @@ func (ph *PatientHandler) LoadLocalData(c echo.Context) error {
func (ph *PatientHandler) HandleShowPatient(c echo.Context) error {
logger, _ := zap.NewProduction()
// userEmail := c.QueryParam("email")
// logger.Info("params", zap.Any("email", userEmail))
listID := utils.GenerateRandomID("listid")
paginationID := utils.GenerateRandomID("paginationid")
dialogID := utils.GenerateRandomID("dialogid")
dialogBodyID := utils.GenerateRandomID("dialogbodyid")
user, err := services.GetUserLogin()
if err != nil {
defer logger.Sync()
logger.Info("Error get user", zap.Any("error", err))
return err
userCok := c.Get("user").(*jwt.Token)
claims := userCok.Claims.(jwt.MapClaims)
name := claims["M_StaffName"].(string)
position := claims["M_UserGroupDashboard"].(string)
logger.Info("jwt", zap.Any("name", name))
user := models.User{
UserID: 1,
Username: name,
UserFullName: name,
UserPosition: position,
}
navbaruser := navbarmenu.NavbarWithLogo(user)

View File

@@ -6,6 +6,7 @@ import (
public_login "cpone/views/public/login"
"encoding/json"
"net/http"
"time"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
@@ -79,6 +80,15 @@ func (lh *LoginHandler) HandleSignIn(c echo.Context) error {
si := public_login.ShowLogin("Login ", public_login.MainLogin(), public_login.CssLogin(), public_login.JsLogin())
return utils.View(c, si)
}
cookie := new(http.Cookie)
cookie.Name = "token"
cookie.Value = resp.Data.Token
cookie.Path = "/"
cookie.HttpOnly = true
c.SetCookie(cookie)
userString := string(user)
store := `
<script>
@@ -94,25 +104,7 @@ func (lh *LoginHandler) HandleSignIn(c echo.Context) error {
setTimeout(() => {
htmx.ajax('GET', '/login/redirect?url=` + url + `')
}, 500)
// document.body.addEventListener('htmx:configRequest', function(evt) {
// evt.detail.headers['Authentication'] = "Bearer: " + getJWT();
// console.log("running");
// });
// setTimeout(() => {
// window.location.href = "` + url + `";
// }, 100);
// document.body.addEventListener('htmx:configRequest', function(evt) {
// const token = localStorage.getItem("token");
// if (token) {
// evt.detail.headers['Authorization'] = "Bearer " + token;
// }
// });
// document.body.hxTrigger({ "hx-redirect": "` + url + `" });
}, 200)
</script>
`
c.Response().Header().Set("HX-Trigger", "script")
@@ -125,7 +117,34 @@ func (lh *LoginHandler) HandleRedirect(c echo.Context) error {
token := c.Request().Header.Get("Authentication")
logger.Info("params", zap.Any("url", url), zap.Any("token", token))
c.Response().Header().Set("Authentication", token)
c.Response().Header().Set("HX-Redirect", url)
return c.String(http.StatusOK, url)
}
func (lh *LoginHandler) HandleSignOut(c echo.Context) error {
logger, _ := zap.NewProduction()
logger.Info("Logout")
expire := time.Now().Add(-7 * 24 * time.Hour)
cookie := new(http.Cookie)
cookie.Name = "token"
cookie.Value = ""
cookie.Path = "/"
cookie.Expires = expire
cookie.HttpOnly = true
c.SetCookie(cookie)
ret := `
<script>
console.log("signout")
localStorage.removeItem("token")
localStorage.removeItem("user")
setTimeout(() => {
window.location.replace("/login");
}, 200)
</script>
`
c.Response().Header().Set("HX-Trigger", "script")
return c.String(http.StatusOK, ret)
}

View File

@@ -1,6 +1,7 @@
package handlers
import (
"cpone/auth"
client_handlers "cpone/handlers/client"
corporate_handlers "cpone/handlers/corporate"
mcu_corporate_handlers "cpone/handlers/corporate/mcudetail"
@@ -78,6 +79,7 @@ func SetupRoutesPublic(app *echo.Echo, appStore db.AppStore) {
public.GET("login", loginHadlr.HandlerShowLogin)
public.POST("login/signin", loginHadlr.HandleSignIn)
public.GET("login/redirect", loginHadlr.HandleRedirect)
public.GET("login/signout", loginHadlr.HandleSignOut)
// kartu kontrol
publicKartuKontrolServices := public_services.NewServicesKartuKontrol(appStore)
@@ -100,7 +102,8 @@ func SetupRoutesPublic(app *echo.Echo, appStore db.AppStore) {
public.GET("redirectsurveymcu", publicKartuKontrolhandlers.HandlerRedirectToSurveyMcu)
}
func SetupRoutesCorporate(app *echo.Echo, appStore db.AppStore) {
corp := app.Group("/corp")
corp := app.Group("/corp", auth.IsLoggedIn)
// corp := app.Group("/corp")
l := corporate_services.NewServicesCompany(appStore)
lh := corporate_handlers.NewCompanyHandler(l)
corp.GET("/company", lh.ShowCompany)
@@ -137,7 +140,7 @@ func SetupRoutesCorporate(app *echo.Echo, appStore db.AppStore) {
}
func SetupRoutesClient(app *echo.Echo, appStore db.AppStore) {
public := app.Group("/client")
public := app.Group("/client", auth.IsLoggedIn)
lpanel := client_services.NewServicesMdPanel(appStore)
lhpanel := client_handlers.NewMdPanelHandler(lpanel)

View File

@@ -151,14 +151,7 @@ templ JSDashboardPat() {
document.getElementById('userEmail').value = parsedData.M_UserEmail;
}
});
document.body.addEventListener('htmx:configRequest', function(evt) {
const token = localStorage.getItem("token");
if (token) {
evt.detail.headers['Authentication'] = "Bearer " + token;
}
});
});
</script>
}

View File

@@ -267,7 +267,7 @@ func JSDashboardPat() templ.Component {
templ_7745c5c3_Var7 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<script>\r\n document.addEventListener(`DOMContentLoaded`, (event) => {\r\n const data = localStorage.getItem(`user`);\r\n if (data) {\r\n const parsedData = JSON.parse(data);\r\n // console.log(parsedData.M_UserEmail);\r\n document.getElementById('userEmail').value = parsedData.M_UserEmail;\r\n \r\n }\r\n });\r\n \r\n\t\tdocument.body.addEventListener('htmx:configRequest', function(evt) {\r\n\t\t\tconst token = localStorage.getItem(\"token\");\r\n\t\t\tif (token) {\r\n\t\t\t\tevt.detail.headers['Authentication'] = \"Bearer \" + token;\r\n\t\t\t}\r\n\t\t});\t \r\n </script>")
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<script>\r\n document.addEventListener(`DOMContentLoaded`, (event) => {\r\n const data = localStorage.getItem(`user`);\r\n if (data) {\r\n const parsedData = JSON.parse(data);\r\n // console.log(parsedData.M_UserEmail);\r\n document.getElementById('userEmail').value = parsedData.M_UserEmail;\r\n \r\n }\r\n }); \r\n </script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}

View File

@@ -94,14 +94,6 @@ templ CssLogin() {
templ JsLogin() {
<script src="/asset-corporate-portal/js/login-general.js"></script>
<script>
document.body.addEventListener('htmx:configRequest', function(evt) {
const token = localStorage.getItem("token");
if (token) {
evt.detail.headers['Authentication'] = "Bearer " + token;
}
});
</script>
}
templ ShowLogin(title string, cmp templ.Component, css templ.Component, js templ.Component) {

View File

@@ -107,7 +107,7 @@ func JsLogin() templ.Component {
templ_7745c5c3_Var3 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<script src=\"/asset-corporate-portal/js/login-general.js\"></script><script>\r\n\t\tdocument.body.addEventListener('htmx:configRequest', function(evt) {\r\n\t\t\tconst token = localStorage.getItem(\"token\");\r\n\t\t\tif (token) {\r\n\t\t\t\tevt.detail.headers['Authentication'] = \"Bearer \" + token;\r\n\t\t\t}\r\n\t\t});\t\r\n\t</script>")
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<script src=\"/asset-corporate-portal/js/login-general.js\"></script>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}