MCPcopy
hub / github.com/writefreely/writefreely / CreateUser

Function CreateUser

app.go:893–950  ·  view source on GitHub ↗

CreateUser creates a new admin or normal user from the given credentials.

(apper Apper, username, password string, isAdmin bool)

Source from the content-addressed store, hash-verified

891
892// CreateUser creates a new admin or normal user from the given credentials.
893func CreateUser(apper Apper, username, password string, isAdmin bool) error {
894 // Create an admin user with --create-admin
895 apper.LoadConfig()
896 connectToDatabase(apper.App())
897 defer shutdown(apper.App())
898
899 // Ensure an admin / first user doesn't already exist
900 firstUser, _ := apper.App().db.GetUserByID(1)
901 if isAdmin {
902 // Abort if trying to create admin user, but one already exists
903 if firstUser != nil {
904 return fmt.Errorf("Admin user already exists (%s). Create a regular user with: writefreely user create [USER]:[PASSWORD]", firstUser.Username)
905 }
906 } else {
907 // Abort if trying to create regular user, but no admin exists yet
908 if firstUser == nil {
909 return fmt.Errorf("No admin user exists yet. Create an admin first with: writefreely user create --admin [USER]:[PASSWORD]")
910 }
911 }
912
913 // Create the user
914 // Normalize and validate username
915 desiredUsername := username
916 username = getSlug(username, "")
917
918 usernameDesc := username
919 if username != desiredUsername {
920 usernameDesc += " (originally: " + desiredUsername + ")"
921 }
922
923 if !author.IsValidUsername(apper.App().cfg, username) {
924 return fmt.Errorf("Username %s is invalid, reserved, or shorter than configured minimum length (%d characters).", usernameDesc, apper.App().cfg.App.MinUsernameLen)
925 }
926
927 // Hash the password
928 hashedPass, err := auth.HashPass([]byte(password))
929 if err != nil {
930 return fmt.Errorf("Unable to hash password: %v", err)
931 }
932
933 u := &User{
934 Username: username,
935 HashedPass: hashedPass,
936 Created: time.Now().Truncate(time.Second).UTC(),
937 }
938
939 userType := "user"
940 if isAdmin {
941 userType = "admin"
942 }
943 log.Info("Creating %s %s...", userType, usernameDesc)
944 err = apper.App().db.CreateUser(apper.App().Config(), u, desiredUsername, "")
945 if err != nil {
946 return fmt.Errorf("Unable to create user: %s", err)
947 }
948 log.Info("Done!")
949 return nil
950}

Callers 2

addUserActionFunction · 0.92
legacyActionsFunction · 0.92

Calls 9

IsValidUsernameFunction · 0.92
connectToDatabaseFunction · 0.85
shutdownFunction · 0.85
getSlugFunction · 0.85
LoadConfigMethod · 0.65
AppMethod · 0.65
GetUserByIDMethod · 0.65
CreateUserMethod · 0.65
ConfigMethod · 0.65

Tested by

no test coverage detected