user auth with pg bcrypt works

This commit is contained in:
Dan Ballard 2015-05-02 10:13:33 -07:00
parent d87901b122
commit e6f858d4fd
2 changed files with 19 additions and 34 deletions

View File

@ -1,2 +1,17 @@
# transmet
Quick fast dirty link store that can dump them to an html template
# install
## DB setup
Create postgress DB and put details in db/dbconf.yml
on that DB
CREATE EXTENSION pgcrypto;
go get bitbucket.org/liamstask/goose/cmd/goose
goose up
## Build and run
go build
sudo cp transmet.conf /etc/init
sudo service transmet start

View File

@ -1,24 +1,11 @@
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
@ -36,41 +23,24 @@ func UsernameExists(db *sql.DB, username string) (bool, error) {
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)
rows, err := db.Query("SELECT username FROM users WHERE username = $1 AND password = crypt($2 ,gen_salt('bf'));", username, password)
if err != nil {
fmt.Println("User DB Error: ", err)
fmt.Println("Username or auth fail: ", err)
return nil
}
var hash_db string
user := User{db: db}
if rows.Next() {
var pw sql.NullString
err := rows.Scan(&user.Username, &pw)
err := rows.Scan(&user.Username)
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)