code.gitea.io/gitea@v1.22.3/models/asymkey/ssh_key_principals.go (about) 1 // Copyright 2021 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package asymkey 5 6 import ( 7 "context" 8 "fmt" 9 "strings" 10 11 "code.gitea.io/gitea/models/db" 12 user_model "code.gitea.io/gitea/models/user" 13 "code.gitea.io/gitea/modules/setting" 14 "code.gitea.io/gitea/modules/util" 15 ) 16 17 // CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines 18 func CheckPrincipalKeyString(ctx context.Context, user *user_model.User, content string) (_ string, err error) { 19 if setting.SSH.Disabled { 20 return "", db.ErrSSHDisabled{} 21 } 22 23 content = strings.TrimSpace(content) 24 if strings.ContainsAny(content, "\r\n") { 25 return "", util.NewInvalidArgumentErrorf("only a single line with a single principal please") 26 } 27 28 // check all the allowed principals, email, username or anything 29 // if any matches, return ok 30 for _, v := range setting.SSH.AuthorizedPrincipalsAllow { 31 switch v { 32 case "anything": 33 return content, nil 34 case "email": 35 emails, err := user_model.GetEmailAddresses(ctx, user.ID) 36 if err != nil { 37 return "", err 38 } 39 for _, email := range emails { 40 if !email.IsActivated { 41 continue 42 } 43 if content == email.Email { 44 return content, nil 45 } 46 } 47 48 case "username": 49 if content == user.Name { 50 return content, nil 51 } 52 } 53 } 54 55 return "", fmt.Errorf("didn't match allowed principals: %s", setting.SSH.AuthorizedPrincipalsAllow) 56 }