settings with rout and use auth and notauth routing with bearer jwt token

This commit is contained in:
valitovgaziz
2024-08-14 12:31:51 +05:00
parent 413e35101c
commit d7ebd35aae
3 changed files with 18 additions and 12 deletions
+1 -1
View File
@@ -22,7 +22,7 @@ func Login(w http.ResponseWriter, r *http.Request) {
} }
// check user // check user
var user models.User var user models.User
if result := psql.PSQL_GORM_DB.Where("username = ?", creds.Email).First(&user); result.Error != nil || !checkPasswordHash(creds.Password, user.Password) { if result := psql.PSQL_GORM_DB.Where("email = ?", creds.Email).First(&user); result.Error != nil || !checkPasswordHash(creds.Password, user.Password) {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }
-1
View File
@@ -39,7 +39,6 @@ func AuthMiddleware(next http.Handler) http.Handler {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)
return return
} }
ctx := context.WithValue(r.Context(), "email", claims.Email) ctx := context.WithValue(r.Context(), "email", claims.Email)
next.ServeHTTP(w, r.WithContext(ctx)) next.ServeHTTP(w, r.WithContext(ctx))
}) })
+17 -10
View File
@@ -27,19 +27,26 @@ func InitChiRouting() {
r.Use(middleware.Heartbeat("/ping")) r.Use(middleware.Heartbeat("/ping"))
r.Use(middleware.NoCache) r.Use(middleware.NoCache)
r.Use(middleware.Recoverer) r.Use(middleware.Recoverer)
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404)
w.Write([]byte("welcome developer! Cool.")) w.Write([]byte("route does not exist"))
})
r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(405)
w.Write([]byte("method is not valid"))
}) })
r.Post("/signin", auth.Register) // public Routes
r.Get("/allusers", admin.GetAllUser) r.Group(func(r chi.Router) {
r.Post("/signup", auth.Register) // register
r.Route("/auth", func(r chi.Router) { r.Post("/signin", auth.Login) // signin
r.Route("/admin", func(r chi.Router) {
r.Get("/allUsers", admin.GetAllUser)
}) })
r.Post("/login", auth.Login)
// Private Routes
// Require Authentication
r.Group(func(r chi.Router) {
r.Use(auth.AuthMiddleware)
r.Get("/allUsers", admin.GetAllUser) // all users get
}) })
// up server on os.Getenv("SERVER_PORT") port on gorutin // up server on os.Getenv("SERVER_PORT") port on gorutin