transmet/user/user.go

93 lines
2.0 KiB
Go

package user
import (
"code.google.com/p/go.crypto/bcrypt"
"crypto/rand"
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func clear(b []byte) {
for i := 0; i < len(b); i++ {
b[i] = 0
}
}
func Crypt(password []byte) ([]byte, error) {
defer clear(password)
return bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
}
type User struct {
Username string
db *sql.DB
}
func UsernameExists(db *sql.DB, username string) (bool, error) {
rows, err := db.Query("SELECT count(username) FROM users where username=$1", username)
if err != nil {
fmt.Println("User DB Error: ", err)
return false, err
}
var count int
rows.Next()
rows.Scan(&count)
return count > 0, nil
}
func GenDisposablePassword() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
fmt.Println("user.GenDisposablePassword() error reading from urandom: ", err)
}
return fmt.Sprintf("%x", b)
}
func NewUserFromAuth(db *sql.DB, username, password string) *User {
fmt.Println("NewUserFromAuth:", username, ":", password)
rows, err := db.Query("SELECT password FROM users WHERE username = $1", username)
if err != nil {
fmt.Println("User DB Error: ", err)
return nil
}
var hash_db string
user := User{db: db}
if rows.Next() {
var pw sql.NullString
err := rows.Scan(&user.Username, &pw)
if err != nil {
fmt.Println("scan err: ", err)
}
hash_db = pw.String
} else {
return nil
}
if err = bcrypt.CompareHashAndPassword([]byte(hash_db), []byte(password)); err == nil {
return &user
}
fmt.Println("auth fail:", err)
return nil
}
func NewUserFromUsername(db *sql.DB, username string) *User {
rows, err := db.Query("SELECT username FROM users WHERE username=$1", username)
if err != nil {
fmt.Println("User DB Error: ", err)
return nil
}
user := User{db: db}
if rows.Next() {
err = rows.Scan(&user.Username)
if err != nil {
fmt.Println("Scan err: ", err)
}
} else {
fmt.Println("User DB Error: No user found with username ", username)
return nil
}
return &user
}