auth/auth.go (view raw)
1package auth
2
3import (
4 "crypto/rand"
5 "encoding/hex"
6 "net/http"
7 "time"
8
9 "golang.org/x/crypto/bcrypt"
10)
11
12type Auth struct {
13 Pepper string
14}
15
16func NewAuth(pepper string) *Auth {
17 return &Auth{
18 Pepper: pepper,
19 }
20}
21
22func (g Auth) HashPassword(password string) (string, error) {
23 hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password+g.Pepper), bcrypt.DefaultCost)
24 if err != nil {
25 return "", err
26 }
27 return string(hashedPassword), nil
28}
29
30func (g Auth) CheckPassword(password, hash string) bool {
31 err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password+g.Pepper))
32 return err == nil
33}
34
35func (g Auth) GenerateRandomToken() (string, error) {
36 token := make([]byte, 32)
37 _, err := rand.Read(token)
38 if err != nil {
39 return "", err
40 }
41 return hex.EncodeToString(token), nil
42}
43
44func (g Auth) GenerateCookie(duration time.Duration) (*http.Cookie, error) {
45 sessionToken, err := g.GenerateRandomToken()
46 if err != nil {
47 return nil, err
48 }
49
50 return &http.Cookie{
51 Name: "session_token",
52 Value: sessionToken,
53 Expires: time.Now().Add(duration),
54 Path: "/",
55 HttpOnly: true,
56 Secure: true,
57 }, nil
58}
59
60func (g Auth) GenerateEmptyCookie() *http.Cookie {
61 return &http.Cookie{
62 Name: "session_token",
63 Value: "",
64 Expires: time.Now().Add(-1 * time.Hour),
65 Path: "/",
66 }
67}