aboutsummaryrefslogtreecommitdiff
path: root/cmd/create-account/main.go
blob: 307fa17e603714fc5cede6261f23d666a2142cd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// Copyright 2017 Vector Creations Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"

	"github.com/sirupsen/logrus"
	"golang.org/x/crypto/bcrypt"
	"golang.org/x/term"

	"github.com/matrix-org/dendrite/setup"
	"github.com/matrix-org/dendrite/setup/config"
	"github.com/matrix-org/dendrite/userapi/api"
	userdb "github.com/matrix-org/dendrite/userapi/storage"
)

const usage = `Usage: %s

Creates a new user account on the homeserver.

Example:

	# provide password by parameter
  	%s --config dendrite.yaml -username alice -password foobarbaz
	# use password from file
  	%s --config dendrite.yaml -username alice -passwordfile my.pass
	# ask user to provide password
	%s --config dendrite.yaml -username alice -ask-pass
	# read password from stdin
	%s --config dendrite.yaml -username alice -passwordstdin < my.pass
	cat my.pass | %s --config dendrite.yaml -username alice -passwordstdin
	# reset password for a user, can be used with a combination above to read the password
	%s --config dendrite.yaml -reset-password -username alice -password foobarbaz

Arguments:

`

var (
	username      = flag.String("username", "", "The username of the account to register (specify the localpart only, e.g. 'alice' for '@alice:domain.com')")
	password      = flag.String("password", "", "The password to associate with the account (optional, account will be password-less if not specified)")
	pwdFile       = flag.String("passwordfile", "", "The file to use for the password (e.g. for automated account creation)")
	pwdStdin      = flag.Bool("passwordstdin", false, "Reads the password from stdin")
	askPass       = flag.Bool("ask-pass", false, "Ask for the password to use")
	isAdmin       = flag.Bool("admin", false, "Create an admin account")
	resetPassword = flag.Bool("reset-password", false, "Resets the password for the given username")
)

func main() {
	name := os.Args[0]
	flag.Usage = func() {
		_, _ = fmt.Fprintf(os.Stderr, usage, name, name, name, name, name, name, name)
		flag.PrintDefaults()
	}
	cfg := setup.ParseFlags(true)

	if *username == "" {
		flag.Usage()
		os.Exit(1)
	}

	pass := getPassword(password, pwdFile, pwdStdin, askPass, os.Stdin)

	accountDB, err := userdb.NewDatabase(
		&config.DatabaseOptions{
			ConnectionString: cfg.UserAPI.AccountDatabase.ConnectionString,
		},
		cfg.Global.ServerName, bcrypt.DefaultCost,
		cfg.UserAPI.OpenIDTokenLifetimeMS,
		api.DefaultLoginTokenLifetime,
	)
	if err != nil {
		logrus.Fatalln("Failed to connect to the database:", err.Error())
	}

	accType := api.AccountTypeUser
	if *isAdmin {
		accType = api.AccountTypeAdmin
	}

	if *resetPassword {
		err = accountDB.SetPassword(context.Background(), *username, pass)
		if err != nil {
			logrus.Fatalf("Failed to update password for user %s: %s", *username, err.Error())
		}
		if _, err = accountDB.RemoveAllDevices(context.Background(), *username, ""); err != nil {
			logrus.Fatalf("Failed to remove all devices: %s", err.Error())
		}
		logrus.Infof("Updated password for user %s and invalidated all logins\n", *username)
		return
	}

	_, err = accountDB.CreateAccount(context.Background(), *username, pass, "", accType)
	if err != nil {
		logrus.Fatalln("Failed to create the account:", err.Error())
	}

	logrus.Infoln("Created account", *username)
}

func getPassword(password, pwdFile *string, pwdStdin, askPass *bool, r io.Reader) string {
	// no password option set, use empty password
	if password == nil && pwdFile == nil && pwdStdin == nil && askPass == nil {
		return ""
	}
	// password defined as parameter
	if password != nil && *password != "" {
		return *password
	}

	// read password from file
	if pwdFile != nil && *pwdFile != "" {
		pw, err := ioutil.ReadFile(*pwdFile)
		if err != nil {
			logrus.Fatalln("Unable to read password from file:", err)
		}
		return strings.TrimSpace(string(pw))
	}

	// read password from stdin
	if pwdStdin != nil && *pwdStdin {
		data, err := ioutil.ReadAll(r)
		if err != nil {
			logrus.Fatalln("Unable to read password from stdin:", err)
		}
		return strings.TrimSpace(string(data))
	}

	// ask the user to provide the password
	if *askPass {
		fmt.Print("Enter Password: ")
		bytePassword, err := term.ReadPassword(int(os.Stdin.Fd()))
		if err != nil {
			logrus.Fatalln("Unable to read password:", err)
		}
		fmt.Println()
		fmt.Print("Confirm Password: ")
		bytePassword2, err := term.ReadPassword(int(os.Stdin.Fd()))
		if err != nil {
			logrus.Fatalln("Unable to read password:", err)
		}
		fmt.Println()
		if strings.TrimSpace(string(bytePassword)) != strings.TrimSpace(string(bytePassword2)) {
			logrus.Fatalln("Entered passwords don't match")
		}
		return strings.TrimSpace(string(bytePassword))
	}

	return ""
}