github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/system/media/streamRemoteAuthorization.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package media 20 21 import ( 22 "bytes" 23 "encoding/json" 24 "io" 25 "net/http" 26 "time" 27 ) 28 29 type AuthorizationReq struct { 30 Proto string `json:"proto,omitempty"` 31 Stream string `json:"stream,omitempty"` 32 Channel string `json:"channel,omitempty"` 33 Token string `json:"token,omitempty"` 34 IP string `json:"ip,omitempty"` 35 } 36 37 type AuthorizationRes struct { 38 Status string `json:"status,omitempty"` 39 } 40 41 func RemoteAuthorization(proto string, stream string, channel string, token string, ip string) bool { 42 43 if !Storage.ServerTokenEnable() { 44 return true 45 } 46 47 buf, err := json.Marshal(&AuthorizationReq{proto, stream, channel, token, ip}) 48 49 if err != nil { 50 return false 51 } 52 53 request, err := http.NewRequest("POST", Storage.ServerTokenBackend(), bytes.NewBuffer(buf)) 54 55 if err != nil { 56 return false 57 } 58 59 request.Header.Set("Content-Type", "application/json; charset=UTF-8") 60 61 client := &http.Client{ 62 Timeout: 1 * time.Second, 63 } 64 65 response, err := client.Do(request) 66 67 if err != nil { 68 return false 69 } 70 71 defer response.Body.Close() 72 73 bodyBytes, err := io.ReadAll(response.Body) 74 75 if err != nil { 76 return false 77 } 78 79 var res AuthorizationRes 80 81 err = json.Unmarshal(bodyBytes, &res) 82 83 if err != nil { 84 return false 85 } 86 87 if res.Status == "1" { 88 return true 89 } 90 91 return false 92 }