-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticate.go
56 lines (45 loc) · 1.2 KB
/
authenticate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
)
type manager interface {
authenticate(username string, password string) (user, error)
}
type userManager struct {
readerWriter
}
const hiddenPassword = "xxxx"
var (
//ErrInvalidUsername is a generic error for inavild username
ErrInvalidUsername = errors.New("Invalid username")
//ErrInvalidPassword is a generic error for inavild passwrod
ErrInvalidPassword = errors.New("Invalid password")
)
func newUserManager(rw readerWriter) userManager {
return userManager{rw}
}
func (u userManager) authenticate(username string, password string) (user, error) {
rr := u.read(username)
if rr.err == ErrNoUsersFound || rr.err == ErrMoreThanOneUserFound {
return user{}, ErrInvalidUsername
}
if rr.err != nil {
return user{}, fmt.Errorf("Error while retrieving user %s: %v", username, rr.err.Error())
}
if rr.user.username == username && rr.user.password == password {
rr.user.password = hiddenPassword
return rr.user, nil
}
return user{}, ErrInvalidPassword
}
func sessionID() string {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
return base64.URLEncoding.EncodeToString(b)
}