1
0
mirror of https://github.com/writeas/web-core synced 2018-07-20 11:55:21 +00:00

Add user authentication helpers

This commit is contained in:
Matt Baer 2015-07-29 17:40:41 -04:00
parent a4eeea7469
commit 2054237757
2 changed files with 42 additions and 0 deletions

21
auth/pass.go Normal file
View File

@ -0,0 +1,21 @@
package auth
import "golang.org/x/crypto/bcrypt"
func clear(b []byte) {
for i := 0; i < len(b); i++ {
b[i] = 0
}
}
func HashPass(password []byte) ([]byte, error) {
// Clear memory where plaintext password was stored.
// http://stackoverflow.com/questions/18545676/golang-app-engine-securely-hashing-a-users-password#comment36585613_19828153
defer clear(password)
// Return hash
return bcrypt.GenerateFromPassword(password, 12)
}
func Authenticated(hash, pass []byte) bool {
return bcrypt.CompareHashAndPassword(hash, pass) == nil
}

21
auth/pass_test.go Normal file
View File

@ -0,0 +1,21 @@
package auth
import "testing"
const pass = "password"
var hash []byte
func TestHash(t *testing.T) {
var err error
hash, err = HashPass([]byte(pass))
if err != nil {
t.Error("Password hash failed.")
}
}
func TestAuth(t *testing.T) {
if !Authenticated(hash, []byte(pass)) {
t.Error("Didn't authenticate.")
}
}