-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.go
60 lines (51 loc) · 1.48 KB
/
auth.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
57
58
59
60
package main
import (
"context"
"crypto/sha512"
"encoding/hex"
"errors"
"github.com/jackc/pgx/v5"
)
var (
ErrInvalidCredentials = errors.New("an authentication error occurred")
)
const ValidatePassword = `SELECT password FROM accounts WHERE mlid = $1 AND password = $2`
// hashPassword hashes the mlchkid for usage in the database.
func hashPassword(password string) string {
hashByte := sha512.Sum512([]byte(password))
return hex.EncodeToString(hashByte[:])
}
// From https://github.com/RiiConnect24/Mail-Go/blob/master/auth.go#L28
// parseSendAuth obtains a mlid and passwd from the given format.
// If it is unable to do so, it returns empty strings for both.
// It additionally determines whether the given mlid is valid -
// if not, it returns empty strings for both values as well.
func parseSendAuth(format string) (string, string) {
match := sendAuthRegex.FindStringSubmatch(format)
if match != nil {
// Format:
// [0] = raw string
// [1] = mlid match
// [2] = passwd match
return match[1], match[2]
} else {
return "", ""
}
}
func validatePassword(ctx context.Context, mlid, password string) error {
if mlid == "" || password == "" {
return ErrInvalidCredentials
}
if !validateFriendCode(mlid[1:]) {
return ErrInvalidCredentials
}
hash := hashPassword(password)
row := pool.QueryRow(ctx, ValidatePassword, mlid[1:], hash)
err := row.Scan(nil)
if errors.Is(err, pgx.ErrNoRows) {
return ErrInvalidCredentials
} else if err != nil {
return err
}
return nil
}