(ctx context.Context, store database.Store, req CreateUserRequest)
| 1923 | } |
| 1924 | |
| 1925 | func (api *API) CreateUser(ctx context.Context, store database.Store, req CreateUserRequest) (database.User, error) { |
| 1926 | // Ensure the username is valid. It's the caller's responsibility to ensure |
| 1927 | // the username is valid and unique. |
| 1928 | if usernameValid := codersdk.NameValid(req.Username); usernameValid != nil { |
| 1929 | return database.User{}, xerrors.Errorf("invalid username %q: %w", req.Username, usernameValid) |
| 1930 | } |
| 1931 | |
| 1932 | // If the caller didn't specify rbac roles, default to |
| 1933 | // a member of the site. |
| 1934 | rbacRoles := []string{} |
| 1935 | if req.RBACRoles != nil { |
| 1936 | rbacRoles = req.RBACRoles |
| 1937 | } |
| 1938 | |
| 1939 | var user database.User |
| 1940 | err := store.InTx(func(tx database.Store) error { |
| 1941 | orgRoles := make([]string, 0) |
| 1942 | |
| 1943 | status := "" |
| 1944 | if req.UserStatus != nil { |
| 1945 | status = string(*req.UserStatus) |
| 1946 | } |
| 1947 | params := database.InsertUserParams{ |
| 1948 | ID: uuid.New(), |
| 1949 | Email: req.Email, |
| 1950 | Username: req.Username, |
| 1951 | Name: codersdk.NormalizeRealUsername(req.Name), |
| 1952 | CreatedAt: dbtime.Now(), |
| 1953 | UpdatedAt: dbtime.Now(), |
| 1954 | HashedPassword: []byte{}, |
| 1955 | RBACRoles: rbacRoles, |
| 1956 | LoginType: req.LoginType, |
| 1957 | Status: status, |
| 1958 | IsServiceAccount: req.ServiceAccount, |
| 1959 | } |
| 1960 | // If a user signs up with OAuth, they can have no password! |
| 1961 | if req.Password != "" { |
| 1962 | hashedPassword, err := userpassword.Hash(req.Password) |
| 1963 | if err != nil { |
| 1964 | return xerrors.Errorf("hash password: %w", err) |
| 1965 | } |
| 1966 | params.HashedPassword = []byte(hashedPassword) |
| 1967 | } |
| 1968 | |
| 1969 | var err error |
| 1970 | user, err = tx.InsertUser(ctx, params) |
| 1971 | if err != nil { |
| 1972 | return xerrors.Errorf("create user: %w", err) |
| 1973 | } |
| 1974 | |
| 1975 | privateKey, publicKey, err := gitsshkey.Generate(api.SSHKeygenAlgorithm) |
| 1976 | if err != nil { |
| 1977 | return xerrors.Errorf("generate user gitsshkey: %w", err) |
| 1978 | } |
| 1979 | _, err = tx.InsertGitSSHKey(ctx, database.InsertGitSSHKeyParams{ |
| 1980 | UserID: user.ID, |
| 1981 | CreatedAt: dbtime.Now(), |
| 1982 | UpdatedAt: dbtime.Now(), |
no test coverage detected