app

package module
v0.0.0-...-193ea26 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 16, 2019 License: AGPL-3.0 Imports: 7 Imported by: 0

README

go-apiExample

A simple Golang API with JWT Bearer, PostgreSQL & GORM

Documentation

Index

Constants

This section is empty.

Variables

View Source
var JwtAuthentication = func(next http.Handler) http.Handler {

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		notAuth := []string{"/api/user/new", "/api/user/login"}

		requestPath := r.URL.Path

		for _, value := range notAuth {
			if value == requestPath {

				next.ServeHTTP(w, r)
				return
			}
		}

		response := make(map[string]interface{})

		tokenHeader := r.Header.Get("Authorization")

		if tokenHeader == "" {

			response = u.Message(false, "Not a valid token")

			w.WriteHeader(http.StatusForbidden)

			w.Header().Add("Content-Type", "application/json")

			u.Respond(w, response)
			return
		}

		splitted := strings.Split(tokenHeader, " ")

		if len(splitted) != 2 {
			response = u.Message(false, "Invalid auth token")
			w.WriteHeader(http.StatusForbidden)
			w.Header().Add("Content-Type", "application/json")
			u.Respond(w, response)
			return
		}

		tokenPart := splitted[1]
		tk := &models.Token{}

		token, err := jwt.ParseWithClaims(tokenPart, tk, func(token *jwt.Token) (interface{}, error) {
			return []byte(os.Getenv("token_password")), nill
		})

		if err != nil {
			response = u.Message(false, "Malformed token")
			w.WriteHeader(http.StatusForbidden)
			w.Header().Add("Content-Type", "application/json")
			u.Respond(w, response)
			return
		}

		if !token.Valid {
			response = u.Message(false, "Token not valid.")
			w.WriteHeader(http.StatusForbidden)
			w.Header().Add("Content-Type", "application/json")
			u.Respond(w, response)
			return
		}

		fmt.Sprintf("User %", tk.Username)
		ctx := context.WithValue(r.Context(), "user", tk.UserId)
		r = r.WithContext(ctx)

		next.ServeHTTP(w, r)
	})
}

JWT Bearer auth

Functions

This section is empty.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL