forgejo/models/user/user_service.go

87 lines
2.2 KiB
Go
Raw Normal View History

2024-02-07 16:12:23 +01:00
// Copyright 2024 The Forgejo Authors. All rights reserved.
2024-02-07 16:42:40 +01:00
// SPDX-License-Identifier: MIT
package user
import (
"context"
2024-02-07 16:42:40 +01:00
"fmt"
"net/url"
"strings"
2024-02-08 09:56:49 +01:00
"code.gitea.io/gitea/models/db"
2024-02-07 16:42:40 +01:00
"code.gitea.io/gitea/models/forgefed"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"github.com/google/uuid"
pwd_gen "github.com/sethvargo/go-password/password"
)
func CreateFederatedUserFromAP(ctx context.Context, person forgefed.ForgePerson,
personID forgefed.PersonID, federationHostID int64) (*User, *FederatedUser, error) {
2024-02-07 16:42:40 +01:00
localFqdn, err := url.ParseRequestURI(setting.AppURL)
if err != nil {
return nil, nil, err
2024-02-07 16:42:40 +01:00
}
email := fmt.Sprintf("f%v@%v", uuid.New().String(), localFqdn.Hostname())
loginName := personID.AsLoginName()
name := fmt.Sprintf("%v%v", person.PreferredUsername.String(), personID.HostSuffix())
log.Info("RepositoryInbox: person.Name: %v", person.Name)
fullName := person.Name.String()
if len(person.Name) == 0 {
fullName = name
}
password, err := pwd_gen.Generate(32, 10, 10, false, true)
if err != nil {
return nil, nil, err
2024-02-07 16:42:40 +01:00
}
user := User{
2024-02-07 16:42:40 +01:00
LowerName: strings.ToLower(person.PreferredUsername.String()),
Name: name,
FullName: fullName,
Email: email,
EmailNotificationsPreference: "disabled",
Passwd: password,
MustChangePassword: false,
LoginName: loginName,
Type: UserTypeRemoteUser,
IsAdmin: false,
}
overwrite := &CreateUserOverwriteOptions{
IsActive: util.OptionalBoolFalse,
IsRestricted: util.OptionalBoolFalse,
}
2024-02-08 09:56:49 +01:00
// Begin transaction
ctx, committer, err := db.TxContext((ctx))
if err != nil {
return nil, nil, err
}
defer committer.Close()
if err := CreateUser(ctx, &user, overwrite); err != nil {
return nil, nil, err
2024-02-07 16:42:40 +01:00
}
federatedUser, err := NewFederatedUser(user.ID, personID.ID, federationHostID)
if err != nil {
return nil, nil, err
2024-02-07 16:42:40 +01:00
}
err = CreateFederationUser(ctx, &federatedUser)
2024-02-07 16:42:40 +01:00
if err != nil {
return nil, nil, err
2024-02-07 16:42:40 +01:00
}
2024-02-08 09:56:49 +01:00
// Commit transaction
committer.Commit()
return &user, &federatedUser, nil
2024-02-07 16:42:40 +01:00
}