eintopf.info@v0.13.16/service/auth/context.go (about) 1 // Copyright (C) 2022 The Eintopf authors 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 <https://www.gnu.org/licenses/>. 15 16 package auth 17 18 import ( 19 "context" 20 "fmt" 21 ) 22 23 type ctxKey string 24 25 const ( 26 ctxKeyID = ctxKey("id") 27 ctxKeyRole = ctxKey("role") 28 ) 29 30 // ContextWithID adds the given id to the context. 31 func ContextWithID(ctx context.Context, id string) context.Context { 32 return context.WithValue(ctx, ctxKeyID, id) 33 } 34 35 // ContextWithRole adds the given role to the context. 36 func ContextWithRole(ctx context.Context, role Role) context.Context { 37 return context.WithValue(ctx, ctxKeyRole, role) 38 } 39 40 // ErrUserIDFromContext is the error, that gets returned by 41 // UserIDFromRequest, when the retrieval fails. 42 var ErrUserIDFromContext = fmt.Errorf("failed to retrieve user id from context") 43 44 // UserIDFromContext retrieves the user id from the given context. 45 // Returns an error on failure. 46 func UserIDFromContext(ctx context.Context) (string, error) { 47 userID, ok := ctx.Value(ctxKeyID).(string) 48 if !ok || userID == "" { 49 return "", ErrUserIDFromContext 50 } 51 return userID, nil 52 } 53 54 // ErrRoleFromContext is the error, that gets returned by 55 // RoleFromRequest, when the retrieval fails. 56 var ErrRoleFromContext = fmt.Errorf("failed to retrieve authorization role from context") 57 58 // RoleFromContext retrieves the authorization role from the given context. 59 // Returns an error on failure. 60 func RoleFromContext(ctx context.Context) (Role, error) { 61 role, ok := ctx.Value(ctxKeyRole).(Role) 62 if !ok || role == "" { 63 return "", ErrRoleFromContext 64 } 65 return role, nil 66 }