Skip to content

Commit

Permalink
Updated auth middleware, added air support
Browse files Browse the repository at this point in the history
  • Loading branch information
Blackmamoth committed Aug 18, 2024
1 parent c63a6f2 commit fac688a
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 12 deletions.
51 changes: 51 additions & 0 deletions .air.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"

[build]
args_bin = []
bin = "./build/tasknet"
cmd = "make build"
delay = 1000
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html"]
include_file = []
kill_delay = "0s"
log = "build-errors.log"
poll = false
poll_interval = 0
post_cmd = []
pre_cmd = []
rerun = false
rerun_delay = 500
send_interrupt = false
stop_on_error = false

[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"

[log]
main_only = false
time = false

[misc]
clean_on_exit = false

[proxy]
app_port = 0
enabled = false
proxy_port = 0

[screen]
clear_on_rebuild = false
keep_scroll = true
7 changes: 6 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,9 @@ build/

# Log files

*.log
*.log
*.zip

# Air

/tmp
21 changes: 11 additions & 10 deletions pkg/handlers/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ func (h *Handler) RegisterRoutes() *chi.Mux {
r.Post("/login", h.login)

r.Group(func(r chi.Router) {
authMiddleware := auth_middleware.New(h.userService)
r.Use(jwtauth.Verifier(utils.AccessTokenAuth))
r.Use(jwtauth.Authenticator(utils.AccessTokenAuth))
r.Use(authMiddleware.VerifyAccessToken)
r.Post("/logout", h.logout)
})

Expand All @@ -53,7 +54,7 @@ func (h *Handler) registerUser(w http.ResponseWriter, r *http.Request) {
var payload validations.RegisterUserSchema

if err := utils.ParseJSON(r, &payload); err != nil {
utils.SendAPIErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("please provide all the required fields"))
utils.SendAPIErrorResponse(w, http.StatusBadRequest, "please provide all the required fields")
return
}

Expand All @@ -80,7 +81,7 @@ func (h *Handler) registerUser(w http.ResponseWriter, r *http.Request) {
hashedPassword, err := utils.HashPassword(payload.Password)

if err != nil {
utils.SendAPIErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("an error occured while processing your password"))
utils.SendAPIErrorResponse(w, http.StatusInternalServerError, "an error occured while processing your password")
return
}

Expand All @@ -102,7 +103,7 @@ func (h *Handler) login(w http.ResponseWriter, r *http.Request) {
var payload validations.LoginUserSchema

if err := utils.ParseJSON(r, &payload); err != nil {
utils.SendAPIErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("please provide all the required fields"))
utils.SendAPIErrorResponse(w, http.StatusBadRequest, "please provide all the required fields")
return
}

Expand All @@ -115,26 +116,26 @@ func (h *Handler) login(w http.ResponseWriter, r *http.Request) {
u, err := h.userService.GetUserByUsername(payload.Username)

if err != nil {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Sprintf("invalid username please check your username and try again"))
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, "invalid username please check your username and try again")
return
}

if !utils.ComparePassword(payload.Password, u.Password) {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Sprintf("invalid password please check your password and try again"))
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, "invalid password please check your password and try again")
return
}

accessToken, err := utils.SignAccessToken(r, u.Id)

if err != nil {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Sprintf("an error occured while processing your credentials"))
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, "an error occured while processing your credentials")
return
}

refreshToken, err := utils.SignRefreshToken(r, u.Id)

if err != nil {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Sprintf("an error occured while processing your credentials"))
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, "an error occured while processing your credentials")
return
}

Expand Down Expand Up @@ -221,14 +222,14 @@ func (h *Handler) refresh(w http.ResponseWriter, r *http.Request) {
accessToken, err := utils.SignAccessToken(r, u.Id)

if err != nil {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Sprintf("an error occured while processing your credentials"))
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, "an error occured while processing your credentials")
return
}

refreshToken, err = utils.SignRefreshToken(r, u.Id)

if err != nil {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Sprintf("an error occured while processing your credentials"))
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, "an error occured while processing your credentials")
return
}

Expand Down
7 changes: 6 additions & 1 deletion pkg/handlers/task/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"

"github.com/blackmamoth/tasknet/pkg/config"
auth_middleware "github.com/blackmamoth/tasknet/pkg/middlewares/auth"
upload_middleware "github.com/blackmamoth/tasknet/pkg/middlewares/upload"
script_model "github.com/blackmamoth/tasknet/pkg/models/script"
"github.com/blackmamoth/tasknet/pkg/types"
Expand Down Expand Up @@ -32,8 +33,10 @@ func New(taskService types.TaskService, userService types.UserService, scriptSer
func (h *Handler) RegisterRoutes() *chi.Mux {
r := chi.NewRouter()

authMiddleware := auth_middleware.New(h.userService)

r.Use(jwtauth.Verifier(utils.AccessTokenAuth))
r.Use(jwtauth.Authenticator(utils.AccessTokenAuth))
r.Use(authMiddleware.VerifyAccessToken)

r.Post("/create", h.createTask)
r.Group(func(r chi.Router) {
Expand Down Expand Up @@ -179,13 +182,15 @@ func (h *Handler) getTasks(w http.ResponseWriter, r *http.Request) {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Errorf("an error occured while authorizing user claims"))
return
}
fmt.Println(claims["user_id"])

tasks, err := h.taskService.GetTasks(payload, claims["user_id"].(string))

if err != nil {
utils.SendAPIErrorResponse(w, http.StatusUnprocessableEntity, fmt.Errorf("an error occured while fetching your tasks: %v", err))
return
}
// fmt.Println(tasks)

data := map[string]interface{}{
"tasks": tasks,
Expand Down
36 changes: 36 additions & 0 deletions pkg/middlewares/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package auth_middleware
import (
"fmt"
"net/http"
"strings"

"github.com/blackmamoth/tasknet/pkg/config"
"github.com/blackmamoth/tasknet/pkg/types"
Expand All @@ -20,6 +21,41 @@ func New(service types.UserService) *Middleware {
}
}

func (m *Middleware) VerifyAccessToken(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
bearer := r.Header.Get("Authorization")
var accessToken string
if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
accessToken = bearer[7:]
} else {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Errorf("unauthorized, no token"))
return
}

token, err := jwtauth.VerifyToken(utils.AccessTokenAuth, accessToken)

if err != nil {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Errorf("invalid access token"))
return
}

userId, ok := token.Get("user_id")
if !ok {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Errorf("invalid access token"))
return
}

_, err = m.service.GetUserById(userId.(string))

if err != nil {
utils.SendAPIErrorResponse(w, http.StatusUnauthorized, fmt.Errorf("invalid refresh token, user not found"))
return
}

next.ServeHTTP(w, r)
})
}

func (m *Middleware) VerifyRefreshToken(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookies := r.Cookies()
Expand Down

0 comments on commit fac688a

Please sign in to comment.