Changeset 329 in code for trunk/service.go


Ignore:
Timestamp:
Jun 8, 2020, 8:30:09 PM (5 years ago)
Author:
delthas
Message:

Add support for the user create admin service command

This adds support for user create, a new service command only accessible
to admin users. This lets users create other users on the fly and makes
soju start the user routine immediately; unlike sojuctl which currently
requires closing soju, creating the user, and starting soju again.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/service.go

    r328 r329  
    163163                        },
    164164                },
     165                "user": {
     166                        children: serviceCommandSet{
     167                                "create": {
     168                                        usage:  "-username <username> -password <password> [-admin]",
     169                                        desc:   "create a new soju user",
     170                                        handle: handleUserCreate,
     171                                        admin:  true,
     172                                },
     173                        },
     174                        admin: true,
     175                },
    165176                "change-password": {
    166177                        usage:  "<new password>",
     
    568579        return nil
    569580}
     581
     582func handleUserCreate(dc *downstreamConn, params []string) error {
     583        fs := newFlagSet()
     584        username := fs.String("username", "", "")
     585        password := fs.String("password", "", "")
     586        admin := fs.Bool("admin", false, "")
     587
     588        if err := fs.Parse(params); err != nil {
     589                return err
     590        }
     591        if *username == "" {
     592                return fmt.Errorf("flag -username is required")
     593        }
     594        if *password == "" {
     595                return fmt.Errorf("flag -password is required")
     596        }
     597
     598        hashed, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost)
     599        if err != nil {
     600                return fmt.Errorf("failed to hash password: %v", err)
     601        }
     602
     603        user := &User{
     604                Username: *username,
     605                Password: string(hashed),
     606                Admin:    *admin,
     607        }
     608        if _, err := dc.srv.createUser(user); err != nil {
     609                return fmt.Errorf("could not create user: %v", err)
     610        }
     611
     612        sendServicePRIVMSG(dc, fmt.Sprintf("created user %q", *username))
     613        return nil
     614}
Note: See TracChangeset for help on using the changeset viewer.