code.vegaprotocol.io/vega@v0.79.0/wallet/service/v2/authorization.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package v2 17 18 import ( 19 "net/http" 20 "strings" 21 22 "code.vegaprotocol.io/vega/wallet/service/v2/connections" 23 ) 24 25 // VWTPrefix is the scheme that prefixes the token in the Authorization HTTP header 26 // It is our non-standard scheme that stands for Vega Wallet Token. 27 const VWTPrefix = "VWT" 28 29 // VWT stands for Vega Wallet Token. It has the following format: 30 // 31 // VWT <TOKEN> 32 // 33 // Example: 34 // 35 // VWT QK6QoNLA2XEZdLFLxkFlq2oTX8cp8Xw1GOzxDAM0aSXxQAR33CGkvDh4vh2ZyQSh 36 type VWT struct { 37 token connections.Token 38 } 39 40 func (t VWT) Token() connections.Token { 41 return t.token 42 } 43 44 func (t VWT) String() string { 45 return VWTPrefix + " " + t.Token().String() 46 } 47 48 func AsVWT(token connections.Token) VWT { 49 return VWT{ 50 token: token, 51 } 52 } 53 54 // ParseVWT parses a VWT into a VWT. If malformed, an error is returned. 55 func ParseVWT(rawVWT string) (VWT, error) { 56 if !strings.HasPrefix(rawVWT, VWTPrefix+" ") { 57 return VWT{}, ErrAuthorizationHeaderOnlySupportsVWTScheme 58 } 59 60 if len(rawVWT) < 5 { 61 return VWT{}, ErrAuthorizationTokenIsNotValidVWT 62 } 63 64 rawToken := trimBlankCharacters(rawVWT[4:]) 65 66 if rawToken == "" { 67 return VWT{}, ErrAuthorizationTokenIsNotValidVWT 68 } 69 70 token, err := connections.AsToken(rawToken) 71 if err != nil { 72 return VWT{}, err 73 } 74 75 return VWT{ 76 token: token, 77 }, nil 78 } 79 80 // ExtractVWT extracts the Vega Wallet Token from the `Authorization` header. 81 func ExtractVWT(r *http.Request) (VWT, error) { 82 rawToken := r.Header.Get("Authorization") 83 if rawToken == "" { 84 return VWT{}, ErrAuthorizationHeaderIsRequired 85 } 86 87 return ParseVWT(rawToken) 88 }