auth

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2019 License: GPL-3.0 Imports: 8 Imported by: 0

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) {
		var sendErrorJson = func(w http.ResponseWriter, errMsg string, httpStatus int) {
			response := make(map[string]interface{})

			response = u.Message(false, errMsg)
			w.WriteHeader(httpStatus)
			w.Header().Add("Content-Type", "application/json")
			u.Respond(w, response)
		}

		notAuth := []string{"", "/", "/api", "/api/user/new", "/api/user/login"}
		requestPath := r.URL.Path

		for _, value := range notAuth {

			if value == requestPath {
				next.ServeHTTP(w, r)
				return
			}
		}

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

		if tokenHeader == "" {
			fmt.Println(r.Header.Get("Sec-WebSocket-Protocol"))
			tokenHeader = r.Header.Get("Sec-WebSocket-Protocol")
			if strings.Contains(tokenHeader, "bearer") && !strings.Contains(tokenHeader, " ") {
				tokenHeader = tokenHeader[:6] + " " + tokenHeader[6:]
			}

		}
		if tokenHeader == "" {
			sendErrorJson(w, "Missing auth token", http.StatusForbidden)
			return
		}

		splitted := strings.Split(tokenHeader, " ")
		if len(splitted) != 2 {
			sendErrorJson(w, "Invalid/Malformed auth token", http.StatusForbidden)
			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")), nil
		})

		if err != nil {
			sendErrorJson(w, "Malformed authentication token", http.StatusForbidden)
			return
		}

		if !token.Valid {
			sendErrorJson(w, "Token is not valid.", http.StatusForbidden)
			return
		}

		account := models.GetUser(tk.UserId)
		if account == nil {
			sendErrorJson(w, "Account linked to the authorization token does not exist (anymore)", http.StatusForbidden)
			return
		}
		if tk.TokenVersion != account.TokenVersion {
			sendErrorJson(w, "Token is not valid anymore.", http.StatusForbidden)
			return
		}

		ctx := context.WithValue(r.Context(), "user", tk.UserId)
		r = r.WithContext(ctx)
		next.ServeHTTP(w, r)
	})
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

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