Files

57 lines
1.4 KiB
Go
Raw Permalink Normal View History

2021-07-24 11:16:34 +01:00
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2021-07-24 11:16:34 +01:00
2021-12-10 16:14:24 +08:00
package asymkey
2021-07-24 11:16:34 +01:00
import (
2023-09-14 19:09:32 +02:00
"context"
2021-07-24 11:16:34 +01:00
"fmt"
"strings"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
2021-07-24 11:16:34 +01:00
"code.gitea.io/gitea/modules/setting"
2022-12-31 12:49:37 +01:00
"code.gitea.io/gitea/modules/util"
2021-07-24 11:16:34 +01:00
)
// CheckPrincipalKeyString strips spaces and returns an error if the given principal contains newlines
2023-09-14 19:09:32 +02:00
func CheckPrincipalKeyString(ctx context.Context, user *user_model.User, content string) (_ string, err error) {
2021-07-24 11:16:34 +01:00
if setting.SSH.Disabled {
2021-12-10 16:14:24 +08:00
return "", db.ErrSSHDisabled{}
2021-07-24 11:16:34 +01:00
}
content = strings.TrimSpace(content)
if strings.ContainsAny(content, "\r\n") {
2022-12-31 12:49:37 +01:00
return "", util.NewInvalidArgumentErrorf("only a single line with a single principal please")
2021-07-24 11:16:34 +01:00
}
// check all the allowed principals, email, username or anything
// if any matches, return ok
for _, v := range setting.SSH.AuthorizedPrincipalsAllow {
switch v {
case "anything":
return content, nil
case "email":
2023-09-14 19:09:32 +02:00
emails, err := user_model.GetEmailAddresses(ctx, user.ID)
2021-07-24 11:16:34 +01:00
if err != nil {
return "", err
}
for _, email := range emails {
if !email.IsActivated {
continue
}
if strings.EqualFold(content, email.LowerEmail) {
2021-07-24 11:16:34 +01:00
return content, nil
}
}
case "username":
if content == user.Name {
return content, nil
}
}
}
return "", fmt.Errorf("didn't match allowed principals: %s", setting.SSH.AuthorizedPrincipalsAllow)
}