Created
November 4, 2013 10:30
-
-
Save veer66/7300759 to your computer and use it in GitHub Desktop.
User management (incomplete)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"crypto/sha1" | |
"code.google.com/p/go.crypto/pbkdf2" | |
"bytes" | |
"labix.org/v2/mgo" | |
"labix.org/v2/mgo/bson" | |
) | |
type User struct { | |
Username string | |
PasswordHash []byte | |
Salt []byte | |
Role string | |
} | |
func generateSalt() []byte { | |
buf := make([]byte, 32) | |
rand.Read(buf) | |
return buf | |
} | |
func generateHash(password string, salt []byte) []byte { | |
buf := bytes.NewBufferString(password) | |
return pbkdf2.Key(buf.Bytes(), salt, 4096, 32, sha1.New) | |
} | |
func AddUser(db *mgo.Database, username string, password string) { | |
salt := generateSalt() | |
user := User{Username: username, | |
Salt: salt, | |
Role: "admin", | |
PasswordHash: generateHash(password, salt)} | |
db.C("user").Insert(user) | |
} | |
func Auth(db *mgo.Database, username string, password string) bool { | |
i := db.C("user").Find(bson.M{"username": username}).Iter() | |
var user User | |
if i.Next(&user) { | |
hash := generateHash(password, user.Salt) | |
return bytes.Equal(hash, user.PasswordHash) | |
} | |
return false | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment