mirror of
https://github.com/usememos/memos.git
synced 2026-11-19 10:29:11 +01:00
e52a507924
A configuration file may now declare which identity-provider subject signs
in as a declared user, as a fourth resource kind:
"linkedIdentities": [
{ "name": "users/admin/linkedIdentities/sso", "externalUid": "subject" }
]
An administrator on an SSO-only instance otherwise has no way in before the
first sign-in, which provisions a new account because the sign-in path
matches a provider and subject and nothing else. Matching an email or
username claim was rejected: neither proves ownership on this instance. A
declared subject trusts no claim, and the sign-in path is unchanged.
Rules: the user must be declared in the same configuration, a subject is
declared once, the provider must exist after apply, and a subject already
linked to a different user fails the plan rather than being taken over. A
link made by signing in with the declared subject is adopted; a different
stored subject is replaced. Links are written after users in the apply
transaction. A declared user with a declared link may be created without a
password; it gets an unusable random one, as SSO provisioning does.
The API refuses to create or delete a managed link, and to delete a
provider a declared link names. The account page hides Unlink for a
declared link. LinkedIdentity.external_uid is no longer output only.
678 lines
23 KiB
Go
678 lines
23 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
stderrors "errors"
|
|
"log/slog"
|
|
"regexp"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/pkg/errors"
|
|
"golang.org/x/crypto/bcrypt"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
"google.golang.org/protobuf/types/known/emptypb"
|
|
|
|
coreuser "github.com/usememos/memos/core/user"
|
|
"github.com/usememos/memos/internal/clientip"
|
|
"github.com/usememos/memos/internal/ratelimit"
|
|
apipb "github.com/usememos/memos/proto/gen/api"
|
|
"github.com/usememos/memos/store"
|
|
)
|
|
|
|
const maxBatchGetUsers = 100
|
|
|
|
const (
|
|
// maxAvatarImageBytes is the largest avatar image a user may set. It
|
|
// matches the limit the web client enforces before encoding the file.
|
|
maxAvatarImageBytes = 2 << 20
|
|
// maxAvatarDataURIBytes bounds the stored data URI: the image bytes
|
|
// base64-encoded (4/3 expansion) plus the "data:<type>;base64," prefix.
|
|
maxAvatarDataURIBytes = maxAvatarImageBytes/3*4 + 256
|
|
)
|
|
|
|
func validateUserTagsSetting(setting *apipb.UserSetting_TagsSetting) error {
|
|
if setting == nil {
|
|
return errors.New("tags setting is required")
|
|
}
|
|
for tag, metadata := range setting.Tags {
|
|
if strings.TrimSpace(tag) == "" {
|
|
return errors.New("tag key cannot be empty")
|
|
}
|
|
if _, err := regexp.Compile(tag); err != nil {
|
|
return errors.Wrapf(err, "tag key %q is not a valid regex pattern", tag)
|
|
}
|
|
if metadata == nil {
|
|
return errors.Errorf("tag metadata is required for %q", tag)
|
|
}
|
|
if metadata.GetBackgroundColor() != nil {
|
|
if err := validateInstanceColor(metadata.GetBackgroundColor()); err != nil {
|
|
return errors.Wrapf(err, "background_color for %q", tag)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *APIService) ListUsers(ctx context.Context, request *apipb.ListUsersRequest) (*apipb.ListUsersResponse, error) {
|
|
currentUser, err := s.fetchCurrentUser(ctx)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
|
|
}
|
|
if currentUser == nil {
|
|
return nil, status.Errorf(codes.Unauthenticated, "user not authenticated")
|
|
}
|
|
if currentUser.Role != store.RoleAdmin {
|
|
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
|
}
|
|
|
|
userFind := &store.FindUser{}
|
|
|
|
if request.Filter != "" {
|
|
username, err := extractUsernameFromFilter(request.Filter)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid filter: %v", err)
|
|
}
|
|
if username != "" {
|
|
userFind.Username = &username
|
|
}
|
|
}
|
|
|
|
var limit, offset int
|
|
if request.PageToken != "" {
|
|
var pageToken apipb.PageToken
|
|
if err := unmarshalPageToken(request.PageToken, &pageToken); err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid page token: %v", err)
|
|
}
|
|
limit = normalizePageSize(pageToken.Limit)
|
|
offset = max(int(pageToken.Offset), 0)
|
|
} else {
|
|
limit = normalizePageSize(request.PageSize)
|
|
}
|
|
// Fetch one extra row to detect whether a subsequent page exists.
|
|
limitPlusOne := limit + 1
|
|
userFind.Limit = &limitPlusOne
|
|
userFind.Offset = &offset
|
|
|
|
users, err := s.Store.ListUsers(ctx, userFind)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to list users: %v", err)
|
|
}
|
|
|
|
nextPageToken := ""
|
|
if len(users) == limitPlusOne {
|
|
users = users[:limit]
|
|
nextPageToken, err = getPageToken(limit, offset+limit)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to get next page token: %v", err)
|
|
}
|
|
}
|
|
|
|
response := &apipb.ListUsersResponse{
|
|
Users: make([]*apipb.User, 0, len(users)),
|
|
NextPageToken: nextPageToken,
|
|
}
|
|
for _, user := range users {
|
|
response.Users = append(response.Users, convertUserFromStore(user, currentUser))
|
|
}
|
|
return response, nil
|
|
}
|
|
|
|
// uniqueBatchUsernames parses user resource names into unique usernames,
|
|
// skipping empty entries.
|
|
func uniqueBatchUsernames(names []string) ([]string, error) {
|
|
uniqueUsernames := make([]string, 0, len(names))
|
|
seen := make(map[string]struct{}, len(names))
|
|
for _, name := range names {
|
|
if name == "" {
|
|
continue
|
|
}
|
|
username, err := parseUsernameFromName(name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if _, ok := seen[username]; ok {
|
|
continue
|
|
}
|
|
seen[username] = struct{}{}
|
|
uniqueUsernames = append(uniqueUsernames, username)
|
|
}
|
|
return uniqueUsernames, nil
|
|
}
|
|
|
|
func (s *APIService) BatchGetUsers(ctx context.Context, request *apipb.BatchGetUsersRequest) (*apipb.BatchGetUsersResponse, error) {
|
|
if len(request.Names) == 0 {
|
|
return &apipb.BatchGetUsersResponse{Users: []*apipb.User{}}, nil
|
|
}
|
|
|
|
nonEmptyNameCount := 0
|
|
for _, name := range request.Names {
|
|
if name != "" {
|
|
nonEmptyNameCount++
|
|
}
|
|
}
|
|
if nonEmptyNameCount > maxBatchGetUsers {
|
|
return nil, status.Errorf(codes.InvalidArgument, "too many names (max %d)", maxBatchGetUsers)
|
|
}
|
|
s.chargeBatch(ctx, nonEmptyNameCount)
|
|
|
|
uniqueUsernames, err := uniqueBatchUsernames(request.Names)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
|
|
}
|
|
|
|
if len(uniqueUsernames) == 0 {
|
|
return &apipb.BatchGetUsersResponse{Users: []*apipb.User{}}, nil
|
|
}
|
|
|
|
normal := store.Normal
|
|
users, err := s.Store.ListUsers(ctx, &store.FindUser{
|
|
UsernameList: uniqueUsernames,
|
|
RowStatus: &normal,
|
|
})
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to list users: %v", err)
|
|
}
|
|
|
|
currentUser, _ := s.fetchCurrentUser(ctx)
|
|
response := &apipb.BatchGetUsersResponse{
|
|
Users: make([]*apipb.User, 0, len(users)),
|
|
}
|
|
for _, user := range users {
|
|
response.Users = append(response.Users, convertUserFromStore(user, currentUser))
|
|
}
|
|
return response, nil
|
|
}
|
|
|
|
func (s *APIService) GetUser(ctx context.Context, request *apipb.GetUserRequest) (*apipb.User, error) {
|
|
user, err := ResolveUserByName(ctx, s.Store, request.Name)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %s", request.Name)
|
|
}
|
|
if user == nil {
|
|
return nil, status.Errorf(codes.NotFound, "user not found")
|
|
}
|
|
currentUser, _ := s.fetchCurrentUser(ctx)
|
|
return convertUserFromStore(user, currentUser), nil
|
|
}
|
|
|
|
func (s *APIService) CreateUser(ctx context.Context, request *apipb.CreateUserRequest) (*apipb.User, error) {
|
|
// Get current user (might be nil for unauthenticated requests)
|
|
currentUser, _ := s.fetchCurrentUser(ctx)
|
|
|
|
if request.User == nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "user is required")
|
|
}
|
|
if request.UserId != "" && request.UserId != request.User.Username {
|
|
return nil, status.Errorf(codes.InvalidArgument, "user_id must match user.username")
|
|
}
|
|
if err := coreuser.ValidateUsername(request.User.Username); err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
|
|
}
|
|
if err := coreuser.ValidatePassword(request.User.Password); err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
|
|
}
|
|
email, err := store.NormalizeEmail(request.User.Email)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
|
|
}
|
|
|
|
roleToAssign := store.RoleUser
|
|
if currentUser != nil && currentUser.Role == store.RoleAdmin {
|
|
// Authenticated ADMIN user can create users with any role specified in request
|
|
if request.User.Role != apipb.User_ROLE_UNSPECIFIED {
|
|
roleToAssign = convertUserRoleToStore(request.User.Role)
|
|
}
|
|
} else {
|
|
limitOne := 1
|
|
allUsers, err := s.Store.ListUsers(ctx, &store.FindUser{Limit: &limitOne})
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to list users: %v", err)
|
|
}
|
|
if len(allUsers) == 0 {
|
|
roleToAssign = store.RoleAdmin
|
|
if !request.ValidateOnly {
|
|
passwordHash, err := bcrypt.GenerateFromPassword([]byte(request.User.Password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to generate password hash: %v", err)
|
|
}
|
|
user, created, err := s.Store.CreateUserIfNoUsers(ctx, &store.User{
|
|
Username: request.User.Username,
|
|
Role: store.RoleAdmin,
|
|
Email: email,
|
|
Nickname: request.User.DisplayName,
|
|
PasswordHash: string(passwordHash),
|
|
})
|
|
if err != nil {
|
|
return nil, convertUserWriteError(err, "failed to create first user")
|
|
}
|
|
if created {
|
|
return convertUserFromStore(user, user), nil
|
|
}
|
|
roleToAssign = store.RoleUser
|
|
}
|
|
}
|
|
|
|
// Only allow user registration if it is enabled in the settings, or if the user is a superuser
|
|
if roleToAssign != store.RoleAdmin {
|
|
instanceGeneralSetting, err := s.Store.GetInstanceGeneralSetting(ctx)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to get instance general setting, error: %v", err)
|
|
}
|
|
if instanceGeneralSetting.DisallowUserRegistration {
|
|
return nil, status.Errorf(codes.PermissionDenied, "user registration is not allowed")
|
|
}
|
|
if instanceGeneralSetting.DisallowPasswordAuth {
|
|
return nil, status.Errorf(codes.PermissionDenied, "password signup is not allowed")
|
|
}
|
|
}
|
|
}
|
|
|
|
// Self-service registration is bounded per address, may require a challenge,
|
|
// and may be vetoed by the instance's signup policy. Admin creation and
|
|
// first-user setup are not.
|
|
if currentUser == nil || currentUser.Role != store.RoleAdmin {
|
|
clientIP := clientip.FromContext(ctx)
|
|
scope := ratelimit.ScopeSignupIP
|
|
if request.ValidateOnly {
|
|
scope = ratelimit.ScopeValidateIP
|
|
}
|
|
if err := s.throttleAndCharge(scope, clientIP, 1); err != nil {
|
|
return nil, err
|
|
}
|
|
if !request.ValidateOnly {
|
|
if err := s.requireChallenge(ctx, ratelimit.ScopeSignupIP); err != nil {
|
|
return nil, err
|
|
}
|
|
if s.SignupPolicy != nil {
|
|
if err := s.SignupPolicy.AllowSignup(ctx, email, clientIP); err != nil {
|
|
return nil, status.Error(codes.PermissionDenied, err.Error())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// If validate_only is true, just validate without creating
|
|
if request.ValidateOnly {
|
|
// Perform validation checks without actually creating the user. The
|
|
// unique index is the guarantee on the real write; this lookup only
|
|
// gives the caller the same answer ahead of time.
|
|
if email != "" {
|
|
holder, err := s.Store.GetUser(ctx, &store.FindUser{Email: &email})
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to check email: %v", err)
|
|
}
|
|
if holder != nil {
|
|
return nil, status.Error(codes.AlreadyExists, emailTakenMessage)
|
|
}
|
|
}
|
|
return &apipb.User{
|
|
Username: request.User.Username,
|
|
Email: email,
|
|
DisplayName: request.User.DisplayName,
|
|
Role: convertUserRoleFromStore(roleToAssign),
|
|
}, nil
|
|
}
|
|
|
|
passwordHash, err := bcrypt.GenerateFromPassword([]byte(request.User.Password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to generate password hash: %v", err)
|
|
}
|
|
|
|
user, err := s.Store.CreateUser(ctx, &store.User{
|
|
Username: request.User.Username,
|
|
Role: roleToAssign,
|
|
Email: email,
|
|
Nickname: request.User.DisplayName,
|
|
PasswordHash: string(passwordHash),
|
|
})
|
|
if err != nil {
|
|
return nil, convertUserWriteError(err, "failed to create user")
|
|
}
|
|
|
|
return convertUserFromStore(user, user), nil
|
|
}
|
|
|
|
func (s *APIService) UpdateUser(ctx context.Context, request *apipb.UpdateUserRequest) (*apipb.User, error) {
|
|
if request.User == nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "user is required")
|
|
}
|
|
if request.UpdateMask == nil || len(request.UpdateMask.Paths) == 0 {
|
|
return nil, status.Errorf(codes.InvalidArgument, "update mask is empty")
|
|
}
|
|
user, err := ResolveUserByName(ctx, s.Store, request.User.Name)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
|
|
}
|
|
if user == nil {
|
|
if request.AllowMissing {
|
|
return nil, status.Errorf(codes.NotFound, "user not found")
|
|
}
|
|
return nil, status.Errorf(codes.NotFound, "user not found")
|
|
}
|
|
userID := user.ID
|
|
currentUser, err := s.fetchCurrentUser(ctx)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
|
|
}
|
|
if currentUser == nil {
|
|
return nil, status.Errorf(codes.Unauthenticated, "user not authenticated")
|
|
}
|
|
// Check permission.
|
|
// Only allow admin or self to update user.
|
|
if currentUser.ID != userID && currentUser.Role != store.RoleAdmin {
|
|
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
|
}
|
|
|
|
if err := s.checkManagedUserChange(ctx, user, request); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
currentTsSec := time.Now().Unix()
|
|
update := &store.UpdateUser{
|
|
ID: user.ID,
|
|
UpdatedTs: ¤tTsSec,
|
|
}
|
|
instanceGeneralSetting, err := s.Store.GetInstanceGeneralSetting(ctx)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to get instance general setting: %v", err)
|
|
}
|
|
passwordChanged := false
|
|
for _, field := range request.UpdateMask.Paths {
|
|
switch field {
|
|
case "username":
|
|
if instanceGeneralSetting.DisallowChangeUsername {
|
|
return nil, status.Errorf(codes.PermissionDenied, "permission denied: disallow change username")
|
|
}
|
|
if err := coreuser.ValidateUsername(request.User.Username); err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
|
|
}
|
|
update.Username = &request.User.Username
|
|
case "display_name":
|
|
if instanceGeneralSetting.DisallowChangeNickname {
|
|
return nil, status.Errorf(codes.PermissionDenied, "permission denied: disallow change nickname")
|
|
}
|
|
update.Nickname = &request.User.DisplayName
|
|
case "email":
|
|
email, err := store.NormalizeEmail(request.User.Email)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
|
|
}
|
|
update.Email = &email
|
|
case "avatar_url":
|
|
// Validate avatar MIME type to prevent XSS during upload
|
|
if request.User.AvatarUrl != "" {
|
|
if len(request.User.AvatarUrl) > maxAvatarDataURIBytes {
|
|
return nil, status.Errorf(codes.InvalidArgument, "avatar exceeds the maximum size of %d bytes", maxAvatarImageBytes)
|
|
}
|
|
imageType, _, err := extractImageInfo(request.User.AvatarUrl)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid avatar format: %v", err)
|
|
}
|
|
// Only allow safe image formats for avatars
|
|
allowedAvatarTypes := map[string]bool{
|
|
"image/png": true,
|
|
"image/jpeg": true,
|
|
"image/jpg": true,
|
|
"image/gif": true,
|
|
"image/webp": true,
|
|
}
|
|
if !allowedAvatarTypes[imageType] {
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid avatar image type: %s. Only PNG, JPEG, GIF, and WebP are allowed", imageType)
|
|
}
|
|
}
|
|
update.AvatarURL = &request.User.AvatarUrl
|
|
case "description":
|
|
update.Description = &request.User.Description
|
|
case "role":
|
|
// Only allow admin to update role.
|
|
if currentUser.Role != store.RoleAdmin {
|
|
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
|
}
|
|
role := convertUserRoleToStore(request.User.Role)
|
|
update.Role = &role
|
|
case "password":
|
|
if err := coreuser.ValidatePassword(request.User.Password); err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "%v", err)
|
|
}
|
|
passwordHash, err := bcrypt.GenerateFromPassword([]byte(request.User.Password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to generate password hash: %v", err)
|
|
}
|
|
passwordHashStr := string(passwordHash)
|
|
update.PasswordHash = &passwordHashStr
|
|
passwordChanged = true
|
|
case "state":
|
|
if currentUser.Role != store.RoleAdmin {
|
|
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
|
}
|
|
rowStatus := convertStateToStore(request.User.State)
|
|
update.RowStatus = &rowStatus
|
|
default:
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid update path: %s", field)
|
|
}
|
|
}
|
|
|
|
updatedUser, err := s.Store.UpdateUser(ctx, update)
|
|
if err != nil {
|
|
if stderrors.Is(err, store.ErrLastSpaceAdmin) {
|
|
return nil, status.Error(codes.FailedPrecondition, "an active space must retain an active administrator")
|
|
}
|
|
if stderrors.Is(err, store.ErrLastInstanceAdmin) {
|
|
return nil, status.Error(codes.FailedPrecondition, lastInstanceAdminMessage)
|
|
}
|
|
return nil, convertUserWriteError(err, "failed to update user")
|
|
}
|
|
if passwordChanged {
|
|
// A new password ends every other session. The caller's own browser
|
|
// session survives when they changed their own password; an admin
|
|
// resetting another account revokes all of that account's sessions.
|
|
keepTokenID := ""
|
|
if currentUser.ID == user.ID {
|
|
keepTokenID = currentRefreshTokenID(ctx, s.Secret)
|
|
}
|
|
if err := s.Store.RemoveUserRefreshTokensExcept(ctx, user.ID, keepTokenID); err != nil {
|
|
slog.Warn("failed to revoke sessions after password change", "user_id", user.ID, "error", err)
|
|
}
|
|
}
|
|
|
|
return convertUserFromStore(updatedUser, currentUser), nil
|
|
}
|
|
|
|
func (s *APIService) DeleteUser(ctx context.Context, request *apipb.DeleteUserRequest) (*emptypb.Empty, error) {
|
|
user, err := ResolveUserByName(ctx, s.Store, request.Name)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.InvalidArgument, "invalid user name: %v", err)
|
|
}
|
|
if user == nil {
|
|
return nil, status.Errorf(codes.NotFound, "user not found")
|
|
}
|
|
userID := user.ID
|
|
currentUser, err := s.fetchCurrentUser(ctx)
|
|
if err != nil {
|
|
return nil, status.Errorf(codes.Internal, "failed to get user: %v", err)
|
|
}
|
|
if currentUser == nil {
|
|
return nil, status.Errorf(codes.Unauthenticated, "user not authenticated")
|
|
}
|
|
if currentUser.ID != userID && currentUser.Role != store.RoleAdmin {
|
|
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
|
|
}
|
|
isSelfDelete := currentUser.ID == userID
|
|
if err := s.checkManagedExistence(ctx, BuildUserName(user.Username)); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := s.checkManagedReference(ctx, BuildUserName(user.Username)); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
deleteResult, err := s.Store.DeleteUser(ctx, &store.DeleteUser{
|
|
ID: user.ID,
|
|
})
|
|
if err != nil {
|
|
if stderrors.Is(err, store.ErrUserHasSpaceMembership) {
|
|
return nil, status.Error(codes.FailedPrecondition, "leave all spaces before deleting this account")
|
|
}
|
|
if stderrors.Is(err, store.ErrLastInstanceAdmin) {
|
|
return nil, status.Error(codes.FailedPrecondition, lastInstanceAdminMessage)
|
|
}
|
|
return nil, status.Errorf(codes.Internal, "failed to delete user: %v", err)
|
|
}
|
|
if isSelfDelete {
|
|
if err := s.clearAuthCookies(ctx); err != nil {
|
|
slog.Warn("failed to clear auth cookies after self delete", "user_id", userID, "error", err)
|
|
}
|
|
}
|
|
if err := s.cleanupDeletedAttachmentStorage(ctx, deleteResult.Attachments); err != nil {
|
|
return nil, status.Errorf(codes.Internal, "user was deleted but attachment storage cleanup failed: %v", err)
|
|
}
|
|
|
|
return &emptypb.Empty{}, nil
|
|
}
|
|
|
|
const emailTakenMessage = "email is already in use"
|
|
|
|
const lastInstanceAdminMessage = "the instance must retain an active administrator"
|
|
|
|
// checkManagedUserChange refuses an update that changes the fields of a user
|
|
// the configuration manages: username, role, and the profile fields its file
|
|
// declares. The password is write-only and never refused. A rename is also
|
|
// refused while a managed resource names the user.
|
|
func (s *APIService) checkManagedUserChange(ctx context.Context, user *store.User, request *apipb.UpdateUserRequest) error {
|
|
changed := []string{}
|
|
for _, path := range request.UpdateMask.Paths {
|
|
switch path {
|
|
case "username":
|
|
if request.User.Username != user.Username {
|
|
changed = append(changed, "username")
|
|
}
|
|
case "display_name":
|
|
if request.User.DisplayName != user.Nickname {
|
|
changed = append(changed, "displayName")
|
|
}
|
|
case "email":
|
|
if email, err := store.NormalizeEmail(request.User.Email); err != nil || email != user.Email {
|
|
changed = append(changed, "email")
|
|
}
|
|
case "role":
|
|
if convertUserRoleToStore(request.User.Role) != user.Role {
|
|
changed = append(changed, "role")
|
|
}
|
|
default:
|
|
}
|
|
}
|
|
if slices.Contains(changed, "username") {
|
|
if err := s.checkManagedReference(ctx, BuildUserName(user.Username)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return s.checkManagedChange(ctx, BuildUserName(user.Username), changed)
|
|
}
|
|
|
|
// convertUserWriteError maps the store's uniqueness sentinels onto
|
|
// AlreadyExists and everything else onto Internal with the given context.
|
|
func convertUserWriteError(err error, context string) error {
|
|
switch {
|
|
case stderrors.Is(err, store.ErrEmailTaken):
|
|
return status.Error(codes.AlreadyExists, emailTakenMessage)
|
|
case stderrors.Is(err, store.ErrUsernameTaken):
|
|
return status.Error(codes.AlreadyExists, "username is already in use")
|
|
default:
|
|
return status.Errorf(codes.Internal, "%s: %v", context, err)
|
|
}
|
|
}
|
|
|
|
func getDefaultUserGeneralSetting() *apipb.UserSetting_GeneralSetting {
|
|
return &apipb.UserSetting_GeneralSetting{
|
|
Locale: "en",
|
|
MemoVisibility: "PRIVATE",
|
|
Theme: "",
|
|
}
|
|
}
|
|
|
|
func (s *APIService) resolveUserFromName(ctx context.Context, name string) (*store.User, error) {
|
|
user, err := ResolveUserByName(ctx, s.Store, name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if user == nil {
|
|
return nil, errors.Errorf("user not found: %s", name)
|
|
}
|
|
return user, nil
|
|
}
|
|
|
|
func (s *APIService) resolveUserAndSettingKeyFromName(ctx context.Context, name string) (*store.User, string, error) {
|
|
parts := strings.Split(name, "/")
|
|
if len(parts) != 4 || parts[0] != "users" || parts[2] != "settings" {
|
|
return nil, "", errors.Errorf("invalid resource name format: %s", name)
|
|
}
|
|
|
|
user, err := s.resolveUserFromName(ctx, BuildUserName(parts[1]))
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
return user, parts[3], nil
|
|
}
|
|
|
|
func (s *APIService) resolveUserAndWebhookIDFromName(ctx context.Context, name string) (*store.User, string, error) {
|
|
parts := strings.Split(name, "/")
|
|
if len(parts) != 4 || parts[0] != "users" || parts[2] != "webhooks" {
|
|
return nil, "", errors.New("invalid webhook name format")
|
|
}
|
|
|
|
user, err := s.resolveUserFromName(ctx, BuildUserName(parts[1]))
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
return user, parts[3], nil
|
|
}
|
|
|
|
func (s *APIService) resolveUserAndLinkedIdentityProviderFromName(ctx context.Context, name string) (*store.User, string, error) {
|
|
parts := strings.Split(name, "/")
|
|
if len(parts) != 4 || parts[0] != "users" || parts[2] != "linkedIdentities" {
|
|
return nil, "", errors.Errorf("invalid linked identity name: %s", name)
|
|
}
|
|
|
|
user, err := s.resolveUserFromName(ctx, BuildUserName(parts[1]))
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
return user, parts[3], nil
|
|
}
|
|
|
|
// linkedIdentityName is the resource name of user's link to the identity
|
|
// provider with uid provider: users/{user}/linkedIdentities/{idp}.
|
|
func linkedIdentityName(user *store.User, provider string) string {
|
|
return coreuser.LinkedIdentityName(user.Username, provider)
|
|
}
|
|
|
|
func convertLinkedIdentityFromStore(user *store.User, identity *store.UserIdentity) *apipb.LinkedIdentity {
|
|
return &apipb.LinkedIdentity{
|
|
Name: linkedIdentityName(user, identity.Provider),
|
|
IdentityProvider: IdentityProviderNamePrefix + identity.Provider,
|
|
ExternalUid: identity.ExternUID,
|
|
}
|
|
}
|
|
|
|
func (s *APIService) resolveUserAndNotificationIDFromName(ctx context.Context, name string) (*store.User, int32, error) {
|
|
parts := strings.Split(name, "/")
|
|
if len(parts) != 4 || parts[0] != "users" || parts[2] != "notifications" {
|
|
return nil, 0, errors.Errorf("invalid notification name: %s", name)
|
|
}
|
|
|
|
user, err := s.resolveUserFromName(ctx, BuildUserName(parts[1]))
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
id, err := strconv.Atoi(parts[3])
|
|
if err != nil {
|
|
return nil, 0, errors.Errorf("invalid notification id: %s", parts[3])
|
|
}
|
|
|
|
return user, int32(id), nil
|
|
}
|