1
// Copyright 2013 Canonical Ltd.
2
// Licensed under the AGPLv3, see LICENCE file for details.
11
"labix.org/v2/mgo/txn"
13
"launchpad.net/juju-core/errors"
14
"launchpad.net/juju-core/utils"
17
var validUser = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9]*$")
19
// AddUser adds a user to the state.
20
func (st *State) AddUser(name, password string) (*User, error) {
21
if !validUser.MatchString(name) {
22
return nil, fmt.Errorf("invalid user name %q", name)
28
PasswordHash: utils.PasswordHash(password),
34
Assert: txn.DocMissing,
37
err := st.runTransaction(ops)
38
if err == txn.ErrAborted {
39
err = fmt.Errorf("user already exists")
47
// getUser fetches information about the user with the
48
// given name into the provided userDoc.
49
func (st *State) getUser(name string, udoc *userDoc) error {
50
err := st.users.Find(D{{"_id", name}}).One(udoc)
51
if err == mgo.ErrNotFound {
52
err = errors.NotFoundf("user %q", name)
57
// User returns the state user for the given name,
58
func (st *State) User(name string) (*User, error) {
60
if err := st.getUser(name, &u.doc); err != nil {
66
// User represents a juju client user.
73
Name string `bson:"_id_"`
77
// Name returns the user name,
78
func (u *User) Name() string {
82
// Tag returns the Tag for
83
// the user ("user-$username")
84
func (u *User) Tag() string {
85
return "user-" + u.doc.Name
88
// SetPassword sets the password associated with the user.
89
func (u *User) SetPassword(password string) error {
90
return u.SetPasswordHash(utils.PasswordHash(password))
93
// SetPasswordHash sets the password to the
94
// inverse of utils.PasswordHash(pwHash).
95
// It can be used when we know only the hash
96
// of the password, but not the clear text.
97
func (u *User) SetPasswordHash(pwHash string) error {
101
Update: D{{"$set", D{{"passwordhash", pwHash}}}},
103
if err := u.st.runTransaction(ops); err != nil {
104
return fmt.Errorf("cannot set password of user %q: %v", u.Name(), err)
106
u.doc.PasswordHash = pwHash
110
// PasswordValid returns whether the given password
111
// is valid for the user.
112
func (u *User) PasswordValid(password string) bool {
113
return utils.PasswordHash(password) == u.doc.PasswordHash
116
// Refresh refreshes information about the user
118
func (u *User) Refresh() error {
120
if err := u.st.getUser(u.Name(), &udoc); err != nil {