github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/auth/common.go (about) 1 /* 2 * Copyright (C) 2023 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package auth 19 20 import ( 21 "errors" 22 "net/http" 23 "strings" 24 25 "github.com/gin-gonic/gin" 26 ) 27 28 // TokenFromContext retrieve token from request Header or Cookie 29 func TokenFromContext(c *gin.Context) (string, error) { 30 token, err := fromHeader(c) 31 if err != nil { 32 return "", err 33 } 34 if token != "" { 35 return token, nil 36 } 37 38 return fromCookie(c) 39 } 40 41 func fromHeader(c *gin.Context) (string, error) { 42 authHeader := c.GetHeader("Authorization") 43 if authHeader == "" { 44 return "", nil // No error, just no token 45 } 46 47 authHeaderParts := strings.Fields(authHeader) 48 if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" { 49 return "", errors.New(`authorization header format must be: "Bearer {token}"`) 50 } 51 52 return authHeaderParts[1], nil 53 } 54 55 func fromCookie(c *gin.Context) (string, error) { 56 token, err := c.Cookie(JWTCookieName) 57 if err == http.ErrNoCookie { 58 // No error, just no token 59 return "", nil 60 } 61 return token, nil 62 }